EF6 批量更新删除数据

首先看改进前的版本以批量更新为例:

[Obsolete]
        public void DeleteRoleUser2(string roleId)
        {
            IRepository<UserEntity> userRepo = RepositoryFactory<UserEntity>.Create();
            IEnumerable<UserEntity> users = userRepo.FindList(x => x.F_RoleId.Equals(roleId));
            foreach (var u in users)
            {
                u.F_RoleId = null;
            }
            userRepo.Update(users, x => x.F_RoleId);
        }

通过miniprofiler检测可以看到:

数据库执行先查询,后多次update 的SQL 操作,耗时84.9ms, 本可以一行update sql 执行的功能却分开成了多次sql执行,效率受到影响。

下面看使用EF-plus的做法,不要用EntityFramework.Extended,会报异常:未能从程序集“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”中加载类型“System.Data.Entity.Core.Mapping.EntityContainerMapping”。且这个Extneded GitHub上明确提示2015年后就不再维护了。

推荐使用 https://entityframework-plus.net/

改进后的批量更新代码如下:

 IRepository<UserEntity> userRepo = RepositoryFactory<UserEntity>.Create();
            Expression<Func<UserEntity, bool>> express = x => x.F_RoleId.Equals(roleId);
            userRepo.Update(express, u => new UserEntity() { F_RoleId= null });

 public int Update<T>(Expression<Func<T, bool>> condition, Expression<Func<T, T>> updateExpression) where T : class, new()
        {
            IQueryable<T> query = dbcontext.Set<T>().Where(condition);
            return  query.Update<T>(updateExpression);            
        }

执行同样的操作,且都是运行后非首次执行比较测试,发现EF plus 效率上要快2~3倍的样子,值得推荐使用。<完>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值