1 DataAnalysisContext context = new DataAnalysisContext(); 2 DateTime date1, date2, date3; 3 for (int i = 0; i < 10; i++) 4 { 5 date1 = DateTime.Now; 6 for (int j = 0; j < 1000; j++) 7 { 8 context.VisitLogs.Add(new VisitLog()); 9 } 10 date2 = DateTime.Now; 11 context.SaveChanges(); 12 date3 = DateTime.Now; 13 Console.WriteLine("Add:{0},Save:{1}", (int)(date2 - date1).TotalMilliseconds, (int)(date3 - date2).TotalMilliseconds); 14 }
输出信息:
Add:907,Save:8909
Add:5640,Save:8702
Add:10734,Save:8752
Add:15841,Save:8695
Add:20978,Save:8754
Add:26066,Save:9053
Add:31178,Save:8597
Add:36250,Save:8639
Add:41369,Save:8728
Add:46564,Save:8698
用SQL Profiler检查一下实际执行的SQL语句
SQL Profiler有观察过,每次都是执行1000次insert,Save时间都差不多,不明白为什么Add的时间怎么会越来越长
@张远强: try
using(DataAnalysisContext context = new DataAnalysisContext()) { }
@dudu: 这样执行起来是正常的,只是奇怪List<VisitLog>.Add每添加千次瞬间就能完成,而EF这么慢
@张远强: EF内部有可以复杂的操作,如果用的不是EF5.0,可以试试EF5.0
@dudu: 手上用的是EF4.4,等用5.0测下看,谢了