Entity with many to many not loading collection property

c#, ef-code-first, entity-framework, entity-framework-4.3, many-to-many

Solution

Make the `Players` property virtual so that EF can lazy load the collection.

public class Roster
{

    //...........

    public virtual ICollection<Player> Players { get; set; }
}

Alternatively you can eager load the `Players` collection.

var rosters = db.Rosters.Include(r => r.Players).ToList();

Problem

I have an entity Roster that has a collection of players. ``` public class Roster { public Roster() { Players = new List<Player>(); } public int RosterId { get; set; } [MaxLength(100)] [Required] public string RosterName { get; set; } public ICollection<Player> Players { get; set; } } public class Player { public int PlayerId { get; set; } [MaxLength(100)] [Required] public string PlayerName { get; set; } public virtual ICollection<Roster> Rosters { get; set; } } ``` I have defined the relationship using the fluent api ``` // many to many Roster - Players modelBuilder.Entity<Roster>() .HasMany(t => t.Players) .WithMany(t=>t.Rosters) .Map(m => { m.ToTable("RosterPlayers"); m.MapLeftKey("RosterId"); m.MapRightKey("PlayerId"); }); ``` I can save a player to a roster like this ``` var roster = rosterRepository.GetById(rosterId); var player = playerRepository.GetById(playerId); roster.Players.Add(player); rosterRepository.Update(roster); ... ``` However, when I retrieve the roster, the players collection is not loaded. I verified the data exists with all the proper values and the following sql does yeild data. ``` SELECT * from Rosters r INNER JOIN RosterPlayers rp on r.RosterId = rp.RosterId INNER JOIN Players p ON p.PlayerId = rp.PlayerId ``` What am I missing?

Original source