实体类型“产品”的实例无法被跟踪,因为已经有一个具有相同键值的实例正在被跟踪。

9
我使用以下代码进行了测试,以更新产品
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 - 实体类型“Product”的实例无法被跟踪,因为已经有另一个具有相同键值的实例正在被跟踪。在附加现有实体时,请确保只附加一个具有给定键值的实体实例。

这是由于查询了existing引起的。是否有解决方案?

4个回答

10

由于您未使用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);

如果您想映射到现有实体:

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

7

AsNoTracking() could help you.


0

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

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

-1

添加代码以进行分离

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


在这种情况下,EntityState 已经分离。 - Amit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接