EF - 批量插入

时间:2022-02-13 01:29:43

比较一下下面两种方式的区别

1,每Add一次 就savechange()

  static void Main(string[] args)
{
//List<User> users= Find1(u => u.NickName.Contains("luo4"));
Stopwatch sw = new Stopwatch();
sw.Start();
using (DB db = new DB())
{
for (int i = 0; i < 1000; i++)
{
User item = new User();
item.NickName = "luo_" + i;
item.RegisterTime = DateTime.Now;
db.User.Add(item);
db.SaveChanges();
}
}
sw.Stop();
Console.WriteLine("运行时间:{0}ms",sw.ElapsedMilliseconds.ToString());
Console.ReadKey();
}

  EF - 批量插入

EF - 批量插入

2,将所有User 添加到db中再统一savechange()

            using (DB db = new DB())
{
for (int i = 0; i < 1000; i++)
{
User item = new User();
item.NickName = "luo_" + i;
item.RegisterTime = DateTime.Now;
db.User.Add(item); }
db.SaveChanges();
}

EF - 批量插入

下面可以看出是少执行了一句Audit Login

EF - 批量插入

Audit:Login

-- network protocol: LPC
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language 简体中文
set dateformat ymd
set datefirst 7
set transaction isolation level read committed