2011-03-21 111 views
15

如果我有下面的类模型...EF 4.1,代码优先:从数据库级联集合预先加载

public class A 
{ 
    public int AId { get; set; } 
    public ICollection<B> BCollection { get; set; } 
} 

public class B 
{ 
    public int BId { get; set; } 
    public ICollection<C> CCollection { get; set; } 
} 

public class C 
{ 
    public int CId { get; set; } 
} 

...是有可能急于加载A类型的对象包含所有级联集合?

我可以包括BCollection像这样:

A a = context.ASet.Where(x => x.AId == 1) 
      .Include(x => x.BCollection) 
      .FirstOrDefault(); 

可我还包括所有莫名其妙的CCollection加载B对象,使我得到A和所有依赖的对象在内存中一个单独的数据库查询?

+0

我在meta上开始了这个问题:http://meta.stackexchange.com/questions/85358/how-to-use-version-specific-tags它与我们以前关于EF中版本特定标记的通信有关。 – 2011-03-30 19:30:36

+0

@拉迪斯拉夫:好的,我会看这个。让我们看看退伍军人是怎么想的。 – Slauma 2011-03-30 20:05:14

回答

22

使用.Include(x => x.BCollection.Select(b => b.CCollection))described here

它也适用于级联。每次需要加载导航属性时,都需要使用.Select

+0

谢谢!对于更深的层次结构,我只需链接Selects,就像这样:'.Include(x => x.BCollection.Select(b => b.CCollection.Select(c => c.DCollection)))',对不对? – Slauma 2011-03-21 15:14:48

+1

@Slauma是的,但链接选择必须是第一选择的唯一项目。您不能同时选择一个实体和一个集合。 Bad例如:.Include(x => x.BCollection.Select(b => new {b.ChildEntity,b.CCollection.Select(c => c.DCollection)})) – Monstieur 2013-03-29 05:11:42