【问题标题】:generic repository - update method通用存储库 - 更新方法
【发布时间】: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 教程中更新通用存储库类中实体的方法 - 在这里我可以访问数据库上下文:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

public virtual void Update(T entityToUpdate)
{
    dbSet.Attach(entityToUpdate);
    context.Entry(entityToUpdate).State = EntityState.Modified;
}

我应该如何修改通用存储库中的更新方法?

【问题讨论】:

    标签: asp.net entity-framework


    【解决方案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();
        }
    

    【讨论】:

    • 或者更好的方法是将该方法添加到通用存储库中: public virtual void Update(T originalEntity, T entityToUpdate) { context.Entry(originalEntity).CurrentValues.SetValues(entityToUpdate); } ??
    • 取决于可能有​​很多场景,您只想修改实体的少数属性,并且在调用 PUT 方法时也只传递这些实体。这就是为什么我喜欢 ODataController 中的 PATCH :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多