Many to many tables in the ENtity Framework
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开发者_StackOverflow 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
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);
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
.
精彩评论