2011-05-11 53 views
22

考慮下面的模型孫子藏品的明確載入中...在EF 4.1

public class Parent 
{ 
    public int Id { get; set; } 
    public ICollection<Child> Children { get; set; } 
} 

public class Child 
{ 
    public int Id { get; set; } 
    public ICollection<Grandchild> Grandchildren { get; set; } 
} 

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

...我們能渴望負荷Include一個Parent所有Children在像這樣一步Grandchildren

context.Parents.Include(p => p.Children.Select(c => c.Grandchildren)) 

是類似的可能明確加載

子集可以明確地加載這樣:

Parent parent = context.Parents.Find(parentId); 
context.Entry(parent).Collection(p => p.Children).Load(); 

但嘗試加載孩子以類似的方式與Include ...

context.Entry(parent) 
    .Collection(p => p.Children.Select(c => c.Grandchildren)).Load(); 

...不編譯和字符串過載Collection ...

context.Entry(parent).Collection("Children.Grandchildren").Load(); 

...拋出一個例外(「......不允許虛線路徑......」)。

,我發現工作的唯一一件事就是明確地加載Grandchildren在一個循環:

Parent parent = context.Parents.Find(parentId); 
context.Entry(parent).Collection(p => p.Children).Load(); 
foreach (var child in parent.Children) 
    context.Entry(child).Collection(c => c.GrandChildren).Load(); 

我想知道如果我錯過了什麼,如果有一些其他的方式來明確地加載在一個往返GrandChildren

感謝您的反饋!

+0

您是否嘗試過'Collection(...)。Query()。Include(...)。Load()'?如果它不工作,恐怕它不被支持。通常'Load'相當於處理來自ObjectContext API的'RelatedEnd.Load'。 – 2011-05-11 15:50:26

+0

@Ladislav:請把這個答案:)它的工作原理! – Slauma 2011-05-11 15:58:51

回答

20

正如我在評論中指出的,您可以嘗試首先查詢關係,然後添加包含並執行加載。例如:

context.Entry(parent) 
     .Collection(p => p.Children) 
     .Query() 
     .Include(c => c.Grandchildren) // I'm not sure if you can include grandchild directly 
     .Load(); 
+0

是的,這正是我在你的評論之後所嘗試的,而且很有效。它打開了這個問題,如果你還可以通過'Include(... Select(...))'加載「GrandGrandChildren」等等。但我猜想它也會起作用。感謝這個解決方案! – Slauma 2011-05-11 16:12:58

+0

我剛剛從你的'IncludeMultiple'(而不是簡單的包含)從這裏測試代碼(http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637# 5376637)與「GrandGrandChildren」和「SomeReferenceInGrandChild」,它的作品呢! – Slauma 2011-05-11 16:34:04

+0

它應該工作,因爲Query()返回實現了'IQueryable'的ObjectQuery',因此它只是EF查詢,只有在某些預定義的條件下才能執行。 – 2011-05-11 19:23:11