How to add child relationships when creating a new object in the Entity Framework – Education Career Blog

I have an entity framework project setup. It it I have four tables and three entities (“A”, “B”, & “C”). There is a 1:n relationship between A and B, and between A and C, and a n:n relationship between B and C.

alt text

I use the following code to try to add a new “B” entity:

A t = null;
if (this.MyA == null)
{
    t = new A()
    {
        EntityKey = this.MyAReference.EntityKey,
        AId = (Guid)this.MyAReference.EntityKey.EntityKeyValues0.Value
    };
}
else
{
    t = this.MyA;
}
this.MyA = null;
context.Attach(t);
this.MyA = t;

The “B” object (“this”) has a child collection of “C” objects. These “C” objects already exist in the database, but are not related to the new object (obviously). When I call “SaveChanges()”, it throws an exception because it tries to add all of the child “C” objects an new objects in the database.

How can I get it to just create the reference in the “Table_JoinBC”, and not try to recreate the “C” objects?

Thanks for any help.

,

Its easier if you use stub entities

You stated that you wanted to add a new B object. And to add a B object you need an A object

Here is an example using stub entities:

A myAObject = new A { A_Id = 5 };

Context.AttachTo("Aes", myAObject);

B myBObject = new B { B_ID = 6, A = myAObject);

Context.AddToBes(myBObject)
Context.SaveChanges();

,

Here is what I got to work, with the child collections:

A myAObject = new A { A_Id = 5 };

Context.AttachTo("Aes", myAObject);

B myBObject = new B () { 
    B_ID = 6, 
    A = myAObject};

foreach( C c_obj in CsCollection){
    Context.AttachTo("Cs", c_obj);
    myBObject.C.Add(c_obj);
}


Context.AddToProducts(myBObject)
Context.SaveChanges();

Thanks.

Leave a Comment