2011-03-21 108 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