O.O
O.O

Reputation: 11287

Entity Framework saving children before parent

Does Entity Framework support saving from bottom up though navigational properties like below? I get a FK constraint error on ORDERID that suggests not. The ORDERID is a FK to ORDERID (but this is not a PK)

someOrderItemEntity.OrderEntity = someOrderEntity;
someOrderItemEntity.ORDERID = someOrderEntity.ORDERID;
context.OrderItems.Add(someOrderItemEntity);
context.SaveChanges();

public partial class OrderEntity
{
    public int ID { get; set; }
    public int ORDERID { get; set; }
    public virtual ICollection<OrderItemEntity> OrderItemEntities{ get; set; }
}

public partial class OrderItemEntity
{
    public int ID { get; set; }
    public int ORDERID { get; set; }

    public virtual OrderEntity OrderEntity{ get; set; }
}

Upvotes: 1

Views: 996

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129667

If you have a FK constraint between the tables, then the parent OrderEntity will have to already exist in the database to add child items the way you are doing.

If you're trying to create both the order and the items at the same time, then I think you need to add the children to the OrderItemEntities collection on the parent OrderEntity. Also make sure that both are in the same context when you call SaveChanges.

Upvotes: 2

Related Questions