实体框架vs ADO.Net与TVP更新多行
问题描述:
我决定将ADO.Net与表值参数代码进行转换,以将多行10,000行更新为Entity Framework,如下面的代码所示。下面的结果表明,它使用ADO.Net TVP不到1秒,而实体框架需要2分钟:34秒。我现在的问题是,如何加快实体框架代码的运行速度,使其与我的ADO.Net一起运行,并使用TVP代码?实体框架vs ADO.Net与TVP更新多行
[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();
}
答
我现在的问题是我怎么加速比我的实体框架代码,以最快的速度我的ADO.Net与TVP代码运行?
你不知道。您可以“下拉”到ADO.NET或TSQL以进行批量操作和复杂的查询。
但通过使用EF来处理大多数查询和事务,仍然可以节省大量时间和精力。
感谢大卫的回答。 – CodingSoft