2016-03-21 59 views
1

我已經定義了以下POCO類,其在許多一對多的關係映射音箱主題:但是EF6上的許多不填充屬性許多

public class Speaker 
{ 
     public int Id { get; set; } 
     public string Firstname { get; set; } 
     public string Surname { get; set; } 

     public virtual ICollection<SpeakerTalkTheme> TalkThemes { get;set; } 
} 

public class SpeakerTalkTheme 
    { 
     [Key, Column(Order = 0)] 
     public int TalkThemeId { get; set; } 

     [Key, Column(Order = 1)] 
     public int SpeakerId { get; set; } 

     public TalkTheme TalkTheme { get; set; } 


     public Speaker Speaker { get; set; } 
    } 
} 

public class TalkTheme 
    { 
     public int Id { get; set; } 
     public string Theme { get; set; } 

     public int Length { get; set; } 

     public virtual ICollection<ThemeTag> ThemeTags { get; set; } 
     public virtual ICollection<SpeakerTalkTheme> TalkThemes { get;set; } 
    } 

,當我查詢數據庫和的WebAPI返回像這樣:

public class SpeakerController : ApiController 
    { 
     public IEnumerable<Speaker> Get() 
     { 
      var db = new MyDbContext(); 
      var model = db.Speakers.Include(x => x.TalkThemes).ToList(); 
      return model; 
     }  
    } 

我得到的主題特性NULL(見下文):

[ 
    { 
    "TalkThemes": [ 
     { 
     "TalkThemeId": 1, 
     "SpeakerId": 1, 
     "TalkTheme": null 
     } 
    ], 
    "Id": 1, 
    "Firstname": "Joe", 
    "Surname": "Bloggs" 
    } 
] 

不應該TalkTheme屬性被填充?它目前只是顯示NULL,我不知道如何得到這個填充。

回答

1

因爲您需要加載另一個級別。不要在你的Include調用如下

//... 
var model = db.Speakers.Include(x => x.TalkThemes.Select(tt=>tt.TalkTheme)).ToList(); 

如果你想看到更多的例子來說明如何加載查詢幾個層次,檢查備註在此msdn page部分。