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

后端 未结 4 601
天命终不由人
天命终不由人 2020-12-21 00:23

I made a test with code below to update the Product:

var existing = await _productRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
if (         


        
相关标签:
4条回答
  • 2020-12-21 00:46

    AsNoTracking() could help you.

    0 讨论(0)
  • 2020-12-21 00:54

    Since you are not using the existing entity, don't load it.

    Use AnyAsync to check if it exists:

    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);
    

    If you want to map to the existing entity:

    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
    
    0 讨论(0)
  • 2020-12-21 00:56

    Check the value of updatedEntity.Id, if it's zero then use the below code.

    var updatedEntity = ObjectMapper.Map<Product>(input);
    updatedEntity.Id = input.Id; //set Id manually
    var entity = await _productRepository.UpdateAsync(updatedEntity);
    
    0 讨论(0)
  • 2020-12-21 01:10

    add code for detaching

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

    0 讨论(0)
提交回复
热议问题