asp.net - Entity framework many-to-many relationship -
ok, i'm trying figure out how setup db properly.
i have 2 classes:
public class event { public int eventid { get; set; } public string eventname { get; set; } }
and
public class dog { public int dogid { get; set; } public string name { get; set; } public int age { get; set; } }
an event must able contain collection of dogs. every dog must able part in event. i'm guessing phone call many-to-many relationship, not how set keys etc. hope i'm clear plenty i'm hoping achieve.
i asked similar question yesterday not clear on needed: have list of objects foreign key.
thanks!
yes, n:n relationship. assuming code first, alter entities:
public class event { public event() { dogs = new hashset<dog>(); } public int eventid { get; set; } public string eventname { get; set; } public virtual icollection<dog> dogs { get; set; } } public class dog { public dog() { events = new hashset<event>(); } public int dogid { get; set; } public string name { get; set; } public int age { get; set; } public virtual icollection<event> events { get; set; } }
and onmodelcreating
:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<dog>() .hasmany(d => d.events) .withmany(e => e.dogs) .map(m => { m.mapleftkey("dogid"); m.maprightkey("eventid"); m.totable("dogevent"); }); }
this should create junction table dogevent
2 foreign keys, dogid
, eventid
asp.net entity-framework
No comments:
Post a Comment