附加类型 'XXX' 的实体失败,因为相同类型的另一个实体已经具有相同的主键值

Attaching an entity of type 'XXX' failed because another entity of the same type already has the same primary key value

当我的代码在以下位置抛出异常时,我卡住了:

dbContext.Entry(entity).State = EntityState.Modified;

我从上个月开始就一直在使用这个代码,但是这个异常是在两天前出现的。我已经阅读了很多主题,但 none 对我有好处。 问题是当尝试更新现有记录时,它总是显示以下错误:

Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

我使用了以下代码:

{
    if (unitOfWork.AddressRepository.DataSet.Where(x => x.AddressId == item.AddressId).ToList().Count() > 0)
       unitOfWork.AddressRepository.Update(item);
    else
       unitOfWork.AddressRepository.Create(item);
}  
public virtual void Update(T entity)
{
    dbContext.Entry(entity).State = EntityState.Modified;
} 

出于测试目的,我还使用“Update”方法进行了实验。

try
{
    dbContext.Entry(entity).State = EntityState.Modified;
}
catch (Exception ex)
{
    Create(entity);
}

public virtual void Create(T entity)
{
    dbSet.Add(entity);
}

//constructor taking the database context and getting the appropriately typed data set from it
public Repository(DBEntities context)
{
    dbContext = context;
    dbSet = context.Set<T>();
}

我已经在构造函数中填充了我的 dbContext。所以我总是在开始时得到 dbContext。

每次执行 Create(entity) 方法都会创建一条新记录。当我签入数据库时​​,记录会重复。

经过两天的努力,我终于得到了解决方案,想分享给大家。

实际上,我使用了 web api 从客户端接收数据,填充模型然后调用 entity.modified。但是 entity framework 只更新它当前的 dbContext。所以起初,我从 dbContext 获取特定数据,然后通过“AutoMapper”更新该特定对象。下面给出的代码解释了一切。

{
   //--get particular data from dbContext 
   var _address = unitOfWork.AddressRepository.GetById(address.AddressId);
   Mapper.CreateMap<Data.Concrete.Address, Data.Concrete.Address>();
   //--update that particular object via autoMapper
   var _customAddress = Mapper.Map<Address, Address>(address, _address);
       if (unitOfWork.AddressRepository.DataSet.Where(x => x.AddressId == address.AddressId).ToList().Count() > 0)
          unitOfWork.AddressRepository.Update(_customAddress);
       else
          unitOfWork.AddressRepository.Create(address);
}