Entity Framework 批量插入很慢吗

2025-05-05 10:56:56
推荐回答(1个)
回答1:

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("

{0}开始将数据Add到上下文中,数据量:{1}

", 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("

{0}数据Added完毕,开始执行Insert操作,耗时{1}

", now2, now2 - now1));
result.Append(string.Format("

AutoDetectChangesEnabled 状态:{0}

", db.Configuration.AutoDetectChangesEnabled));
try
{
db.SaveChanges();
}
finally
{
db.Configuration.AutoDetectChangesEnabled = true;
db.Configuration.ValidateOnSaveEnabled = true;
}

var now3 = DateTime.Now.TimeOfDay;
result.Append(string.Format("

{0}Insert完毕,耗时{1}

", now3, now3 - now2));

ViewBag.result = result.ToString();

return View();
}