Knightsy Knightsy - 8 months ago 52
C# Question

How to get entity framework inserting in correct order with one to many and one to one from same models

Here are the basic models:


public virtual int OrderGroupId { get; protected set; }
public virtual ICollection<Order> Orders { get; set; }
public virtual Order UnpricedOrder { get; set; }


public virtual int OrderId { get; protected set; }
public virtual int OrderGroupId { get; protected set; }
public virtual OrderGroup OrderGroup { get; set; }

And in fluent API:

// Order group config
var orderGroup = modelBuilder.Entity<OrderGroup>();
orderGroup.HasOptional(og => og.UnpricedOrder)
.Map(og => og.MapKey("UnpricedOrderId"));

// Order config
var order = modelBuilder.Entity<Order>();
order.HasRequired(o => o.OrderGroup)
.WithMany(og => og.Orders)
.HasForeignKey(o => o.OrderGroupId);

So an orderGroup has many of its own orders, each order belongs to a group, and an order group may optionally reference a single unpriced order.

I have one order, already in an orderGroup, that was saved to the database already.

I now create a second 'unpriced' order, give it it's own group and then call save changes.

Entity framework tries to insert the unpriced order first, before its own order group and a foreign key error occurs.

As a human its clear to me that
a) When saving an order - its order group must be created first

I imagine entity framework is getting muddled up because if I was saving an order group AND it had an unpriced order then the order of insert would need to be
Unpriced Orders' Order Group -> Unpriced Order -> Order Group -> It's orders.

How can I get entity framework to save in the correct order when the parent needs to be saved first sometimes - but not every time.

Answer Source

We never found a way around this. In the end we used a bridging table/model to get this to work.

So we had a OrderOrderGroup table (wish we had gone with a simpler name) where each row required an OrderId and an OrderGroupId. We then had a third column describing the relationship. So an Order was either omitted from an order group (because it was unpriced), or it belonged to an order group.

Entity framework could then cope with this and knew to save the order and order group, before then saving the OrderOrderGroup.