无法跟踪实体类型“产品"的实例,因为已跟踪具有相同键值的另一个实例 [英] The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked

查看:32
本文介绍了无法跟踪实体类型“产品"的实例,因为已跟踪具有相同键值的另一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码进行了测试以更新 Product:

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 - 无法跟踪实体类型Product"的实例,因为已经跟踪了另一个具有相同 {'Id'} 键值的实例.附加现有实体时,请确保仅附加一个具有给定键值的实体实例.

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.

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

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

推荐答案

由于您没有使用 existing 实体,请不要加载它.

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

使用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 实体:

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

这篇关于无法跟踪实体类型“产品"的实例,因为已跟踪具有相同键值的另一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆