none
Entity Framework 4.0 and self-referencing tables; .SaveChanges() fails on .AddObject() RRS feed

  • Question

  • PROBLEM SUMMARY:

    When using self-referencing relationships and attempting to add objects, .SaveChanges() fails with “Unable to determine the principle end of the ‘PlannerModel.FK_PlanItem_PlanItem’ relationship. Multiple added entities may have the same primary key.”.

    PROBLEM DETAILS:


    // --------- Code ----------

    plannerContext = new PlannerEntities2();

    var unitPlanQuery = from d in plannerContext.UnitPlans
                                    where d.TeacherId == sourceTeacherId
                                    orderby d.TeacherId
                                    select d;


    var planItem = new PlanItem();
    ClonePlanItem(pi, planItem); // where pi is original PlanItem

    planItem.ParentPlanItem = (PlanItem)planItemsAddedHT[pi.ParentPlanItemId];

    // above object on right is the previously added PlanItem

    plannerContext.PlanItems.AddObject(planItem);


    plannerContext.SaveChanges();

    // -----------End Code ------------

    I went back to my code and commented it up such that I knew for sure only a single call to ‘plannerContect.PlanItems.AddObject(planItem)’ was taking place. Thus there was only a single object to insert. The error message changed to:

    “Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.”


    I went back and added “Allow Nulls” to the ParentPlanItemId column in SQL Management Studio (SQL Server 2008 btw), and refreshed my model…but this did not make a difference.

    Table:  PlanItem

    -------------------

    PlanItem int  PK, identity

    ParentPlanItemID int  , allow null

    ItemText varchar(200)

     

    Referential Constraint from Model Designer:  Principal = PlanItem; Principal Key = PlanItemId; Dependant Property = ParentPlanItemId

     

    Association from Model Designer:

    AssociationSet Name:   FK_PlanItem_PlanItem

    End1 Multipllicity:  1(One Of PlanItem)

    End1 Navigation prop: PlanItem1

    End2 Multuplicity: * (Collection of PlanItem)

    End2 Nav: ParentPlanItem

    Name: FK_PlanItem_PlanItem

     

    Thursday, April 14, 2011 11:01 PM

Answers

  • The answer is:

     

    for self-referencing tables...the multiplicity needs to be (zero to 1) and the parentplanitemid field needs to allow null..... and you should send NULL...and not zero as that breaks the constraint.

     

     

    Tuesday, April 19, 2011 12:10 PM

All replies

  • The answer is:

     

    for self-referencing tables...the multiplicity needs to be (zero to 1) and the parentplanitemid field needs to allow null..... and you should send NULL...and not zero as that breaks the constraint.

     

     

    Tuesday, April 19, 2011 12:10 PM
  • Thanks for sharing your answer :)
    Wednesday, April 20, 2011 1:51 AM