Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a child entity in EntityFramework 4?

I have a 1-1 relationship between Orders and Contact. i.e. Contact.OrderId references Orders and is also a PK.

So I have an existing Order and I add a new Contact to it like so...

    order.Contact = new Contact() { EmailAddress = "hello" };
    context.Orders.Attach(order);
    context.SaveChanges();

A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.

So what am I doing wrong?

like image 463
Ian Warburton Avatar asked Oct 11 '22 07:10

Ian Warburton


2 Answers

Just generate your child entity, set its OrderIdReference property and you should be good to go.

like image 97
Robert Koritnik Avatar answered Oct 15 '22 09:10

Robert Koritnik


You have a 1-to-1 relationship with shared primary key in Order and Contact table: The PK of a contact must always be the same as the PK of the associated order. This has some consequences:

  • Only one of the PK columns in Order and Contact table can be an autogenerated identity. I assume it is the Order table.
  • If order already had a Contact before you assign the new one, you must delete the old contact explicitely from the database because you cannot have two contacts with the same OrderId since it is the PK at the same time.
  • Because Contact table doesn't have an identity column you must supply the PK manually in code and it must be the PK of the order.

To put this together, it might look like:

context.Orders.Attach(order);
if (order.Contact != null)
    context.DeleteObject(order.Contact);
order.Contact = new Contact() { OrderId = order.Id, EmailAddress = "hello" };
context.SaveChanges();

This assumes that 1) the old order.Contact is loaded into the order object if there was already a Contact before you assign a new one and 2) that the property OrderId of Contact is the PK property.

like image 41
Slauma Avatar answered Oct 15 '22 11:10

Slauma