【发布时间】:2014-07-06 17:35:22
【问题描述】:
我有对象:orderToEdit(使用来自用户的值)和 originalOrder(使用来自数据库的值)——它们当然具有相同的主键。我想使用用户的新值更新现有记录。但我不能,因为 originalOrder 由实体框架跟踪,所以我有错误:
> An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
>
> Additional information: Attaching an entity of type 'Blog.Model.Entities.Orders' 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.
服务中的方法 - 这里我无权访问数据库上下文:
public void EditOrder(Orders orderToEdit) // orderToEdit object has values from user
{
Orders originalOrder = _ordersService.GetOrder(orderToEdit.OrderId);
if (originalOrder == null)
{
throw new HttpException(404);
}
orderToEdit.CreateDate = originalOrder.CreateDate;
_unitOfWork.OrdersRepository.Update(orderToEdit); // Update method it is the method which you can see below
_unitOfWork.Save();
}
这是在 Microsoft 教程中更新通用存储库类中实体的方法 - 在这里我可以访问数据库上下文:
public virtual void Update(T entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
我应该如何修改通用存储库中的更新方法?
【问题讨论】: