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

醉酒当歌 提交于 2020-01-10 05:11:14

问题


I made a test with code below to update the 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);

But it throws an exception:

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.

This is caused by querying existing. Is there any solution for this?


回答1:


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



回答2:


AsNoTracking() could help you.




回答3:


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


来源:https://stackoverflow.com/questions/49798566/the-instance-of-entity-type-product-cannot-be-tracked-because-another-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!