none
Saving parent with new child object, getting referential integrity errors RRS feed

  • Question

  • The way I work with EF is to setup my entity objects detached from objectcontext in my presentation layer (ie in my MVC controller etc) and then calling a service/repositry class which will attach it to context, and save it (including doing any other generic property settigns like creating log records etc). This is Ef5 / .NET 4.5.

    The problems is when I try to save a parent where I have added a new child (child is added outside context). When I attach the parent with db.Entry(myParent).State = EnityState.Modified, I get an referential integrity error "The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship". Have been doing something like this with EF 3.5 without any problems (however handling foreign keys from child to parent was more of a problem there).

    Also it looks like the collection of child objecs are lazy loaded automatically (which is not wanted because there might be many).

    My "save method" take the parent entity as parameter, sometimes I only save parent and sometimed I might have a child object as well.

    A workaround I used was to move the child objectinto a variable and doing a clear on the collection before attaching parent to context. Then I add the child object to context and after that adding child to parent's collection (does this cause lazy loading of collection?).

    What is the recommended method to do this?

    Wednesday, February 27, 2013 10:31 AM

Answers

  • Hi Magnusb999,

    Welcome to the MSDN forum.

    Please try to use Add method instead of Attach method to add detached entity into context. Then please set the state of parent as Unchanged or Modified: context.Entry(parent).State = EntityState.Unchanged;

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Alexander Sun Monday, March 11, 2013 8:21 AM
    Thursday, February 28, 2013 9:37 AM