Entity Framework 批量插入很慢

Entity Framework 批量插入很慢吗?我自己测试下

 

前几天看到一篇文章里提到过,在批量插入时,需要加上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();
        }
原文地址:https://www.cnblogs.com/dogxuefeng/p/3123619.html