2011-05-11 120 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