Entity Framework 对比 ADO.Net TVP 更新多行

Entity Framework vs ADO.Net with TVP Updating Multiple Rows

我决定将我的 ADO.Net 和 Table 值参数代码转换为 Entity Framework,如下面的代码所示。下面的结果显示 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();
    } 

My question now is how do I speedup my Entity Framework code to run as fast as my ADO.Net with TVP code?

你不知道。您 "drop down" 到 ADO.NET 或 TSQL 用于批量操作和复杂查询。

但通过使用 EF 处理您的大部分查询和事务,仍然可以节省大量时间和精力。