views:

30

answers:

2

Greetings,

I'm having a hard time with the ADO.NET Entity framework. I want to do a relation between 2 existing items, in a Many to Many table.

Example:

create table A(key int, value varchar(10));
create table B(key int, value varchar(10));

create table A_B(keyA int, keyB int);-- those are FK..

Now I want to do the relation between them, in the Entitie Framework, I've tried

A_B ab=new A_B{a=new A{key=1},b=new B{key=2}}

But I get 2 new elements in the A and B table.

How can I do this?

Thank you in advance

+1  A: 

There should be 2 entities in you model class A and class B. Each having a navigation property containing a collection of another type.

So you can do like this

 var a = new A();
 var b = new B();

 a.CollectionOfB.Add(b);

or

 b.CollectionOfA.Add(a); 
Yury Tarabanko
That won't fix his problem. It will still put two new objects in the A and B table, instead of using existing objects.
Craig Stuntz
+1  A: 

The easy way is to load the entities:

A_B ab = new A_B{a= Context.As.Single(a => a.key=1), Context.Bs.Single(b => b.key=2)};

However, developers who like to prematurely optimize frequently fear that the performance overhead of 2 DB reads will crush their application and try to use stub entities. When you do this, you must attach them to the context:

var a = new A{key=1};
Context.AttachTo("As", a);
var b = new B{key=2};
Context.AttachTo("Bs", b);
A_B ab = new A_B{a = a, b = b};

EF 4 lets you do this without the strings using CreateObjectSet.

Craig Stuntz