EF自动探测更改

本文介绍如何通过禁用Entity Framework的自动状态探测功能来显著提升批量插入操作的性能,并提供了具体的代码示例。在批量操作前后切换AutoDetectChangesEnabled属性,可以有效避免不必要的资源消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/donaldjohn/p/6651450.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值