如何显式加载所有集合项的导航属性?

时间:2012-06-26 09:33:01

标签: c# entity-framework-4 ef-code-first

这是示例模型类,它们与Entity Framework Code First一起使用:

public class Master
{
  public int Id { get; set; }
  public Collection<Detail> Details { get; set; }
}

public class Detail
{
  public int Id { get; set; }
  public Master Master { get; set; }
  public SubDetail SubDetail1 { get; set; }
  public SubDetail SubDetail2 { get; set; }
}

public class SubDetail
{
  public int Id { get; set; }
}

我想明确加载Master及其所有细节和子细节。要加载我正在使用Include的详细信息:

context.Masters.Include("Details").Where(master => master.Id == 1);

我应该使用什么来加载子细节?

1 个答案:

答案 0 :(得分:1)

尝试

context.Masters.Include(m => m.Details.Select(d => d.SubDetail1))
   .Include(m => m.Details.Select(d => d.SubDetail2))
   .Where(master => master.Id == 1);

非通用版

context.Masters.Include("Details.SubDetail1")
   .Include("Details.SubDetail2")
   .Where(master => master.Id == 1);