当我的代码在以下位置抛出异常时,我陷入了困境:
dbContext.Entry(entity).State = EntityState.Modified;
自上个月以来我一直在使用此代码,但仅在两天前才出现此异常。我已经阅读了很多主题,但没有一个对我有益。问题是当尝试更新现有记录时,它总是显示以下错误:
附加类型为“X”的实体失败,因为相同类型的另一个实体已具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“Attach”方法或将实体状态设置为“Unchanged”或“Modified”时可能会发生这种情况。这可能是因为某些实体是新的,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。
我使用了以下代码:
{
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;
}
出于测试目的,我还使用“更新”方法进行了实验。
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 apis 从客户端接收数据,填充模型然后调用 entity.modified。但是实体框架只更新其当前的 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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句