gbro3n
gbro3n

Reputation: 6967

Entity Framework - How to NOT update related objects

I have the following simple Create method in my repository. The behaviour that I want to prevent is the insertion of related objects at the same time that the target object (OrderItem) is inserted.

In this case, the Order item has a reference property - Product. When the OrderItem record is created, so is a Product record.

How can I disassociate the two so that only the OrderItem is inserted?

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

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

    return orderItem;
}

Upvotes: 2

Views: 198

Answers (1)

Jaycee
Jaycee

Reputation: 3118

You can detach the Product property from the context:

this.DbContext.Entry(orderItem.Product).State = EntityState.Detached;

Upvotes: 2

Related Questions