views:

24

answers:

2

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.EntityKeyValues[0].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.

+1  A: 

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();
John Hartsock
A useful tip, but it does not appear to solve the problem. I have tried several different configurations with no luck.
Sako73
@Sako73... I just updated my answer with an example on how to add a new B object using STUB Entities
John Hartsock
A: 

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.

Sako73