前幾天看到一篇文章里提到過,在批量插入時,需要加上Context.Configuration.AutoDetectChangesEnabled = false;
文章原話:EF默認會自動的跟蹤數據的變化,當變更的數據量較大的時候,EF的跟蹤工作量就會驟增,但指定操作變得非常緩慢(這也是部分同學懷疑EF的性能問題的一個懷疑點),其實,只要在批量操作的時候把自動更新關閉,即可解決緩慢的問題。
大家自己去看看:http://www.cnblogs.com/guomingfeng/archive/2013/05/28/mvc-ef-repository.html 由於沒測試,所以不知道結果是不是變快,快多少
結果早上發現首頁一個測試Entity Framework的文章,http://www.cnblogs.com/newton/archive/2013/06/06/3120497.html 說EF性能不行,正好沒加這句,我也好奇,所以自己測試下,寫這個文章不是針對作者,只是自己好奇,互相討論
測試結果
Context.Configuration.AutoDetectChangesEnabled = false 時,果然是拖拉機變灰機啊。。。
不知道這樣測試對不對,反正確實快了不少
后台代碼
public ActionResult Index(int args, string check) { int count = args; EF_Test test = new EF_Test(); Random ra = new Random(); System.Text.StringBuilder result = new System.Text.StringBuilder(); var now1 = DateTime.Now.TimeOfDay; result.Append(string.Format("<p>{0}開始將數據Add到上下文中,數據量:{1}</p>", now1, count)); if (check != null) { db.Configuration.AutoDetectChangesEnabled = false; db.Configuration.ValidateOnSaveEnabled = false; } for (int i = 0; i < count; i++) { test = new EF_Test(); test.Name = "linfei"; test.Date = DateTime.Now; test.RandomNum = ra.Next(1, 10) * 100; db.EF_Test.Add(test); } var now2 = DateTime.Now.TimeOfDay; result.Append(string.Format("<p>{0}數據Added完畢,開始執行Insert操作,耗時{1}</p>", now2, now2 - now1)); result.Append(string.Format("<p>AutoDetectChangesEnabled 狀態:{0}</p>", db.Configuration.AutoDetectChangesEnabled)); try { db.SaveChanges(); } finally { db.Configuration.AutoDetectChangesEnabled = true; db.Configuration.ValidateOnSaveEnabled = true; } var now3 = DateTime.Now.TimeOfDay; result.Append(string.Format("<p>{0}Insert完畢,耗時{1}</p>", now3, now3 - now2)); ViewBag.result = result.ToString(); return View(); }