entity framework - Specify an association table in Code First -
consider scenario entity called list can hold many user.
public class list{ public int id{get;set;} public string name{get;set;} public virtual list<user>users{get;set; } public class user{ public int id{get;set;} public string name{get;set;} public virtual list<list>list{get;set; }
i have association table called listuserassociation in db , contains multiple records.
the table has 2 columns listid , userid
how specify association in ef code first?
p.s . cannot drop , recreate table.
since have collections defined on both sides, can define relationship either side:
modelbuilder.entity<list>().hasmany(e => e.users).withmany(e => e.list).map(ca => ca.mapleftkey(new string[] {"listid"}).maprightkey(new string[] {"userid"}).totable("listuserassociation"); modelbuilder.entity<user>().hasmany(e => e.list).withmany(e => e.users).map(ca => ca.mapleftkey(new string[] {"userid"}).maprightkey(new string[] {"listid"}).totable("listuserassociation");
i believe need 1 line or other in order define relationship. though redundant, prefer include both lines see relationship defined either entity (i place of mapping code in separate classes each entity).
Comments
Post a Comment