How do I save a child entity in EntityFramework 4?

耗尽温柔 提交于 2019-12-12 08:10:26

问题


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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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();


来源:https://stackoverflow.com/questions/5679703/how-do-i-save-a-child-entity-in-entityframework-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!