我定义了以下POCO类,它们以多对多的关系将演讲者映射到主题:
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;
}
}
我在themes属性中得到NULL(见下文):
[
{
"TalkThemes": [
{
"TalkThemeId": 1,
"SpeakerId": 1,
"TalkTheme": null
}
],
"Id": 1,
"Firstname": "Joe",
"Surname": "Bloggs"
}
]
不应填充TalkTheme属性吗?它目前只显示NULL,我不知道如何填充这个。
答案 0 :(得分:1)
因为你需要加载另一个级别。在Include
电话中执行以下操作:
//...
var model = db.Speakers.Include(x => x.TalkThemes.Select(tt=>tt.TalkTheme )).ToList();
如果您想查看有关如何在查询中加载多个级别的更多示例,请查看此msdn page中的备注部分。