entity framework 4.1 - EF 4.1 Code First Mapping two columns in one table to list -


i'm having issue figuring out how make work ef 4.1 code first. i've looked around , found similar problem, couldn't work me , sounds didn't answered person either.

here simplified version of 2 objects in question.

public class team {   public int teamid {get; set;}   public virtual ilist<game> games {get; set;} }  public class game {   public int gameid {get; set; }   public int awayteamid {get; set;}   public int hometeamid {get; set;}    public virtual team hometeam { get; set; }   public virtual team awayteam { get; set; }   } 

and here code registering fks

protected override void onmodelcreating(dbmodelbuilder modelbuilder) {     modelbuilder.entity<game>()         .hasrequired(a => a.hometeam)         .withmany()         .hasforeignkey(u => u.hometeamid).willcascadeondelete(false);      modelbuilder.entity<game>()         .hasrequired(a => a.awayteam)         .withmany()         .hasforeignkey(u => u.awayteamid).willcascadeondelete(false); } 

i want bring games (home or away) team in. right ef creating teamid column in database never gets populated. if want impossible, lists of homegames , awaygames , list of games combination of two, i'd try , avoid if possible. i'm still learning explanations or tips appreciated.

ef not able map 2 relations single navigation property. additional teamid column created because games navigation property considered separate relation (your mapping says neither hometeam or awayteam part of relation) instructed ef create 3 relations your.

you must define model way:

public class team {   public int teamid {get; set;}   public virtual icollection<game> homegames { get; set; }   public virtual icollection<game> awaygames { get; set; } } 

and mapping must be:

protected override void onmodelcreating(dbmodelbuilder modelbuilder) {     modelbuilder.entity<game>()         .hasrequired(a => a.hometeam)         .withmany(t => t.homegames)         .hasforeignkey(u => u.hometeamid).willcascadeondelete(false);      modelbuilder.entity<game>()         .hasrequired(a => a.awayteam)         .withmany(t => t.awaygames)         .hasforeignkey(u => u.awayteamid).willcascadeondelete(false); } 

now if want team's games can use simply:

var games = team.homegames.concat(team.awaygames); 

you can wrap method returning ienumerable or property getter returning ienumerable.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -