开发者

How do I save a child entity in EntityFramework 4?

开发者 https://www.devze.com 2023-02-25 15:52 出处:网络
I have a 1-1 relationship between Orders and Contact. i.e. Contact.OrderId references Orders and is also a PK.

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:

  • 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.


Just a guess but i think you need to set the pk for your contact object. Entity framework doesnt like it when you dont have Primary keys null.


The new contract has not been added:

context.Orders.Attach(order);
context.AddToContractSet(order.Contract);
context.SaveChanges();

This is assuming that order is already in the DB, and you are attaching because it originally came from another context. If not, just do this:

context.AddToORdersSet(order);
context.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号