实体框架与ADO.Net与TVP更新多行

时间:2017-05-18 23:55:58

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

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

enter image description here

[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();
    } 

1 个答案:

答案 0 :(得分:1)

  
    

我现在的问题是如何使用TVP代码加快我的实体框架代码的运行速度和ADO.Net一样快?

  

你不是。你&#34;下拉&#34; ADO.NET或TSQL用于批量操作和复杂查询。

但是,通过在大多数查询和交易中使用EF,仍然可以节省大量的时间和精力。