EF Core 查询再保存报错

使用EF CORE查询再保存时报错:

System.InvalidOperationException:“The instance of entity type 'VManager' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.”

错误源代码:

        public void EdidManager(VManagerDto vManagerDto) {

            VManager vManager = _TEntityRepository.Where(c => c.Id == vManagerDto.Id).FirstOrDefault();
            if (vManager==null) {
                throw new ControllerException("未查询到相关数据");
            }
            if (vManager.TelePhone!=vManagerDto.TelePhone) {
                if (_TEntityRepository.Where(c => c.TelePhone == vManagerDto.TelePhone&&c.Id!=vManagerDto.Id).Count() > 0)
                {
                    throw new ControllerException("手机号已存在,请换一个");
                }
            }
            if (vManager.PassWord!=vManagerDto.PassWord) {

                if (!Regex.IsMatch(vManagerDto.PassWord, RegularExpression.StrongPwdChar))
                {
                    throw new ControllerException(RegularExpression.StrongPwdCharMessage);
                }
                vManagerDto.Salt = Utils.GetCheckCode(16);
                vManagerDto.PassWord = Common.Encrypt.AesHelper.Encrypt(vManagerDto.PassWord, vManagerDto.Salt);
           
            }
             var  newvManager = AutoMapper.Mapper.Map<VManagerDto, VManager>(vManagerDto);
            //_TEntityRepository.Attach(newvManager);
            _TEntityRepository.Update(newvManager);
            _unitOfWork.Commit();
            var userKey = $"user:{newvManager.Id}";
            RedisHelper.DeleteKey(userKey);
        }

 

查阅相关资料后发现:

是因为修改数据的时候对数据进行了一次查询才导致的

在查询时使用 AsNoTracking()完美解决,以此笔记备忘

修改后源代码

 VManager vManager = _TEntityRepository.AsNoTracking().Where(c => c.Id == vManagerDto.Id).FirstOrDefault();

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值