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

Tao*_*hou 4 c# entity-framework change-tracking asp.net-boilerplate aspnetboilerplate

我使用以下代码进行了测试以更新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);
Run Code Online (Sandbox Code Playgroud)

但这会引发异常:

Mvc.ExceptionHandling.AbpExceptionFilter-无法跟踪实体类型'Product'的实例,因为已经跟踪了另一个具有相同键值的{'Id'}实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

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

小智 7

AsNoTracking() 可以帮助你。


aar*_*ron 6

由于您没有使用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);
Run Code Online (Sandbox Code Playgroud)

如果要映射到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
Run Code Online (Sandbox Code Playgroud)

  • 我解决了`var updatedEntity = ObjectMapper.Map(input, existing);` (2认同)