EF批量更新优化

时间:2021-05-14 16:45:53

未优化修改:

static void Main(string[] args)
        {
            DateTime startDateTime = DateTime.Now;
            using (studyEntities study = new studyEntities())
            {
                //study.Configuration.AutoDetectChangesEnabled = false;
                var users = study.Users.Where(x=>x.Id>0);
                foreach (var item in users)
                {
                    item.Name = "你我他";
                }
                DateTime insetLocalDateTime = DateTime.Now;
                TimeSpan local = insetLocalDateTime - startDateTime;
                Console.WriteLine("数量" + 10000 + " 本地添加到数据上下文耗时 " + local.TotalMinutes + " 分钟 = " + local.TotalSeconds + " 秒");
                study.SaveChanges();
                DateTime insetDataDateTime = DateTime.Now;
                TimeSpan data = insetDataDateTime - insetLocalDateTime;
                Console.WriteLine("数量" + 10000 + " 数据库添加完成耗时" + data.TotalMinutes + " 分钟 = " + data.TotalSeconds + " 秒");
            }
        }

EF批量更新优化

优化 在添加到数据上下文,关闭 AutoDetectChangesEnabled ,提交之前 开启 AutoDetectChangesEnabled 

static void Main(string[] args)
        {
            DateTime startDateTime = DateTime.Now;
            using (studyEntities study = new studyEntities())
            {
                study.Configuration.AutoDetectChangesEnabled = false;
                var users = study.Users.Where(x=>x.Id>0);
                foreach (var item in users)
                {
                    item.Name = "你我他2";
                }
                DateTime insetLocalDateTime = DateTime.Now;
                TimeSpan local = insetLocalDateTime - startDateTime;
                Console.WriteLine("数量" + 10000 + " 本地添加到数据上下文耗时 " + local.TotalMinutes + " 分钟 = " + local.TotalSeconds + " 秒");
                study.Configuration.AutoDetectChangesEnabled = true;
                study.SaveChanges();
                DateTime insetDataDateTime = DateTime.Now;
                TimeSpan data = insetDataDateTime - insetLocalDateTime;
                Console.WriteLine("数量" + 10000 + " 数据库添加完成耗时" + data.TotalMinutes + " 分钟 = " + data.TotalSeconds + " 秒");
            }
        }
EF批量更新优化

因此修改,不必关闭检测更新