【发布时间】: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