【问题标题】:Entity Framework vs ADO.Net with TVP Updating Multiple Rows实体框架与 ADO.Net 与 TVP 更新多行
【发布时间】:2017-05-18 23:55:57
【问题描述】:

我决定将我的 ADO.Net 与表值参数代码转换为实体框架,如下面的代码所示,以更新 10,000 行的多行。下面的结果表明,ADO.Net TVP 用时不到 1 秒,而 Entity Framework 用时 2 分钟:34 秒。我现在的问题是如何使用 TVP 代码加速我的 Entity Framework 代码以与我的 ADO.Net 一样快?

[Table("Employee")]
public class Employee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string Lastname { get; set; }
    public string Town { get; set; }
    public string PostCode { get; set; }
}

public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>();


        Stopwatch stopwatch = Stopwatch.StartNew();

        for (int i = 1; i <= 10000; i++)
        {

            Employee emp = new Employee();

            emp.EmployeeId = i;
            emp.FirstName = "FirstName" + i;
            emp.Lastname = "Lastname" + i;
            emp.Town = "Town" + i;
            emp.PostCode = "PostCode" + i;

            employees.Add(emp);

        }

        var e = employees.OrderBy(o => Convert.ToInt32(o.EmployeeId)).ToList();
        SaveEmployeeToDatabase(e, "EmployeeDB");
        stopwatch.Stop();
        string t = stopwatch.Elapsed.ToString();
        Console.WriteLine("Time Elapse: " + t + ": " + "ADO.Net Update Multiple Rows with TVP");


        /*Entity Entity Framework Update Multiple Rows*/

        EmployeeContext db = new EmployeeContext();

        Stopwatch stopwatch1 = Stopwatch.StartNew();

        for (int i = 1; i <= 10000; i++)
        {

            Employee emp1 = new Employee();

            emp1.EmployeeId = i;
            emp1.FirstName = "NewFirstName" + i;
            emp1.Lastname = "NewLastname" + i;
            emp1.Town = "NewTown" + i;
            emp1.PostCode = "NewPostCode" + i;

            db.Employees.Add(emp1);
            db.Entry(emp1).State = EntityState.Modified;

        }

        db.SaveChanges();
        stopwatch1.Stop();
        string t1 = stopwatch1.Elapsed.ToString();
        Console.WriteLine("Time Elapse: " + t1 + ": " + "Entity Framework Update Multiple Rows");
        Console.Read();
    } 

【问题讨论】:

    标签: c# .net entity-framework ado.net


    【解决方案1】:

    我现在的问题是如何使用 TVP 代码加速我的 Entity Framework 代码以与我的 ADO.Net 一样快地运行?

    你没有。您“下拉”到 ADO.NET 或 TSQL 以进行批量操作和复杂查询。

    但使用 EF 进行大部分查询和交易仍然可以节省大量时间和精力。

    【讨论】:

    • 感谢大卫的回答。
    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多