EF默认会跟踪实体的状态变化, 个别情况下如果将AutoDetectChangesEnabled设置为false将会禁用自动状态探测, 大大的提高性能.
保存数据前应该用cbContext.ChangeTracker.DetectChanges();手动探测状态变化, 不要手动实体状态, 容易出错!!! 我就遇到了下面的异常.
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0).
在批量插入时可以用过如下的方法提高性能:
using (var context = new BloggingContext())
{
try
{
context.Configuration.AutoDetectChangesEnabled = false;
// Make many calls in a loop
foreach (var blog in aLotOfBlogs)
{
context.Blogs.Add(blog);
}
}
finally
{
context.Configuration.AutoDetectChangesEnabled = true;
}
}
参考链接
https://msdn.microsoft.com/en-us/data/jj556205.aspx
http://stackoverflow.com/questions/16863382/dbcontext-autodetectchangesenabled-set-to-false-detecting-changes