[英]The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked
I made a test with code below to update the Product
:我用下面的代码进行了测试以更新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. Mvc.ExceptionHandling.AbpExceptionFilter - 无法跟踪实体类型 'Product' 的实例,因为已经跟踪了具有相同 {'Id'} 键值的另一个实例。 When attaching existing entities, ensure that only one entity instance with a given key value is attached.附加现有实体时,请确保仅附加一个具有给定键值的实体实例。
This is caused by querying existing
.这是由查询existing
. Is there any solution for this?有什么解决办法吗?
Since you are not using the existing
entity, don't load it.由于您没有使用existing
实体,因此不要加载它。
Use AnyAsync
to check if it exists:使用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);
If you want to map to the existing
entity:如果要映射到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()
可以帮助你。
Check the value of updatedEntity.Id
, if it's zero then use the below code.检查updatedEntity.Id
的值,如果它为零,则使用以下代码。
var updatedEntity = ObjectMapper.Map<Product>(input);
updatedEntity.Id = input.Id; //set Id manually
var entity = await _productRepository.UpdateAsync(updatedEntity);
add code for detaching添加用于分离的代码
_dbcontext.Entry(oldEntity).State = EntityState.Detached; _dbcontext.Entry(oldEntity).State = EntityState.Detached;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.