I'm having an issue figuring out how to make this work for EF 4.1 Code First. I've looked around and found a similar problem, but I couldn't get it to work for me and it sounds like it didn't get answered for this person either.
Here is a simplified version of the two 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 is my code for registering the 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 to bring back all games (home or away) that a team is in. Right now EF is creating a TeamId column in my database that never gets populated. If what I want is impossible, then I could do lists of HomeGames and AwayGames and another list of Games that is a combination of the two, but I'd like to try and avoid it if possible. I'm still learning this so any extra explanations or tips would be appreciated.