首页 > 其他 > 详细

EF自动探测更改

时间:2017-03-31 15:48:13      阅读:254      评论:0      收藏:0      [点我收藏+]

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

EF自动探测更改

原文:http://www.cnblogs.com/donaldjohn/p/6651450.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!