我有对象: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;
}
我应该如何修改通用存储库中的Update方法?
答案 0 :(得分:1)
使用修改后的订单填写您从数据库获得的原始订单,并将其保存为
public void EditOrder(Orders orderToEdit) // orderToEdit object has values from user
{
Orders originalOrder = _ordersService.GetOrder(orderToEdit.OrderId);
if (originalOrder == null)
{
throw new HttpException(404);
}
//Fill the originalOrder with the modified One like
originalOrder.CreateDate = orderToEdit.CreateDate; // Do same with other properties
//Now save the original order
_unitOfWork.OrdersRepository.Update(originalOrder);
_unitOfWork.Save();
}