实体框架 - 如何不更新相关对象

时间:2013-11-01 11:14:15

标签: c# entity-framework-5

我的存储库中有以下简单的Create方法。我想要阻止的行为是在插入目标对象(OrderItem)的同时插入相关对象。

在这种情况下,Order项具有引用属性 - Product。创建OrderItem记录时,产品记录也是如此。

如何解除两者的关联以便只插入OrderItem?

public OrderItem Create(OrderItem orderItem, int orderID)
{
    orderItem.CreatedDate = DateTime.Now;
    orderItem.OrderID = orderID;

    this.DbContext.OrderItems.Add(orderItem);
    this.DbContext.SaveChanges();

    return orderItem;
}

1 个答案:

答案 0 :(得分:2)

您可以从上下文中分离Product属性:

this.DbContext.Entry(orderItem.Product).State = EntityState.Detached;
相关问题