【问题标题】:The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked无法跟踪实体类型“产品”的实例,因为已在跟踪具有相同键值的另一个实例
【发布时间】:2018-04-12 13:58:53
【问题描述】:

我用下面的代码做了一个测试来更新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 - 无法跟踪实体类型“Product”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

这是由查询existing 引起的。有什么解决办法吗?

【问题讨论】:

    标签: c# entity-framework aspnetboilerplate change-tracking asp.net-boilerplate


    【解决方案1】:

    由于您没有使用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
    

    【讨论】:

    • 我通过var updatedEntity = ObjectMapper.Map(input, existing);解决了
    【解决方案2】:

    AsNoTracking() 可以帮到你。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        添加分离代码

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

        【讨论】:

        • 在这种情况下,EntityState 已经分离。
        猜你喜欢
        • 2022-01-02
        • 2023-01-03
        • 1970-01-01
        • 2018-06-20
        • 1970-01-01
        • 1970-01-01
        • 2016-08-19
        • 2021-11-24
        相关资源
        最近更新 更多