entity framework - how to do many to many with the same table with EF4 Code First -


i have schema:

create table person ( id int identity primary key, name nvarchar(30) )  create table personpersons ( personid references person(id), childpersonid references person(id) ) 

how create classes map them using ef4 code first ctp5 ?

for poco...

class person {     public guid personid { get; set; }     public virtual person parent { get; set; }     public virtual icollection<person> children { get; set; } } 

...set mapping in dbcontext...

protected override void onmodelcreating(modelbuilder modelbuilder) {     modelbuilder.entity<person>()         .hasoptional(entity => entity.parent)             .withmany(parent => parent.children)             .hasforeignkey(parent => parent.personid); } 

...will give default implementation. if need rename table explicitly (and want many-to-many relationship), add in this...

class person {     public guid personid { get; set; }     public virtual icollection<person> parent { get; set; }     public virtual icollection<person> children { get; set; } }  protected override void onmodelcreating(modelbuilder modelbuilder) {     configureproducts(modelbuilder);     configuremembership(modelbuilder);      modelbuilder.entity<person>()         .hasmany(entity => entity.children)         .withmany(child => child.parent)         .map(map =>         {             map.totable("personpersons");             map.mapleftkey(left => left.personid, "personid");              map.maprightkey(right => right.personid, "childpersonid");             // ef5, comment 2 above lines , uncomment 2 below lines.             // map.mapleftkey("personid");             // map.maprightkey("childpersonid");         });  } 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -