3

我有一個實體名單,有一個球員的集合。實體與多對多沒有加載集合屬性

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; } 
} 

我已經定義了使用的流暢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"); 
}); 

我可以一個玩家保存到名冊這樣

var roster = rosterRepository.GetById(rosterId); 
var player = playerRepository.GetById(playerId); 

roster.Players.Add(player); 
rosterRepository.Update(roster); 
... 

不過的關係,當我取回名冊,球員集合未加載。我驗證了數據存在與所有適當的值和下面的sql does yeild數據。

SELECT * from Rosters r 
INNER JOIN RosterPlayers rp on r.RosterId = rp.RosterId 
INNER JOIN Players p ON p.PlayerId = rp.PlayerId 

我錯過了什麼?

回答

10

使Players屬性爲虛擬,以便EF可以延遲加載集合。

public class Roster 
{ 

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

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

或者,您可以急切加載Players集合。

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

DOH!...你花這麼多時間看有時候最簡單的問題就是被忽視。謝謝 – jason

相關問題