无法跟踪实体类型 'Product' 的实例,因为已跟踪具有相同键值的另一个实例

The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked

我用下面的代码进行了测试以更新 Product:

var existing = await _productRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
if (existing == null)
    throw new UserFriendlyException(L("ProductNotExist"));
var updatedEntity = ObjectMapper.Map<Product>(input);
var entity = await _productRepository.UpdateAsync(updatedEntity);

但是抛出异常:

Mvc.ExceptionHandling.AbpExceptionFilter - The instance of entity type 'Product' 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.

这是查询existing造成的。有解决办法吗?

检查 updatedEntity.Id 的值,如果它为零则使用下面的代码。

var updatedEntity = ObjectMapper.Map<Product>(input);
updatedEntity.Id = input.Id; //set Id manually
var entity = await _productRepository.UpdateAsync(updatedEntity);

因为您没有使用 existing 实体,所以不要加载它。

使用AnyAsync检查是否存在:

var exists = await _productRepository.GetAll().AnyAsync(c => c.Id == input.Id); // Change
if (!exists)                                                                    // this
    throw new UserFriendlyException(L("ProductNotExist"));

var updatedEntity = ObjectMapper.Map<Product>(input);
var entity = await _productRepository.UpdateAsync(updatedEntity);

如果要映射到 existing 实体:

var existing = await _productRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
if (existing == null)
    throw new UserFriendlyException(L("ProductNotExist"));

var updatedEntity = ObjectMapper.Map(input, existing); // Change this

AsNoTracking() 可以帮到你。

添加分离代码

_dbcontext.Entry(oldEntity).State = EntityState.Detached;