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?
Just generate your child entity, set its OrderIdReference
property and you should be good to go.
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:
Order
and Contact
table can be an autogenerated identity. I assume it is the Order
table.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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With