I am working on a simple MVC application using Entity Framework to track the scores of a Badminton league. I have the following two classes:
public class Game
{
public int Id { get; set; }
public Player Player1 { get; set; }
public Player Player2 { get; set; }
public int Player1Score { get; set; }
public int Player2Score { get; set; }
}
and
public class Player
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public List<Game> Games { get; set; }
}
The problem I have is when I have an instance of a player the Games property is returning an empty list. When I request my list of players I use the following:-
var players = badmintonDB.Players.Include("Games").ToList();
From a search on SO I have attempted to override OnModelCreating
. I have tried the following with and without the Map()
. This creates another table in my database but it doesn't contain any records.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Player>().HasMany(p => p.Games).WithMany()
.Map(m =>
{
m.ToTable("PlayerGames");
m.MapLeftKey("Player_Id");
m.MapRightKey("Game_Id");
});
base.OnModelCreating(modelBuilder);
}
I cannot see where I am going wrong, whether I need to rethink the design of my POCO's or if I have the syntax wrong when overriding OnModelCreating
.
Any help would be appreciated.