使用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();