Entity Framework 批量插入很慢吗
展开全部
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();
}
{
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();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询