孙子藏品在EF 4.1明确加载 [英] Explicit loading of grandchild collections in EF 4.1
问题描述
考虑下面的模型......
Given the following model ...
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; }
}
...我们能贪婪加载与包含
A 父
所有孩子
和孙子
一步到位,像这样:
... we can eager load with Include
a Parent
with all Children
and Grandchildren
in one step like so:
context.Parents.Include(p => p.Children.Select(c => c.Grandchildren))
是类似的东西可能对于明确加载
子集合可以明确地装载这种方式:
The child collection can be explicitely loaded this way:
Parent parent = context.Parents.Find(parentId);
context.Entry(parent).Collection(p => p.Children).Load();
但尝试加载孩子以同样的方式与包含
...
context.Entry(parent)
.Collection(p => p.Children.Select(c => c.Grandchildren)).Load();
...不编译UND 收集的字符串超载
...
context.Entry(parent).Collection("Children.Grandchildren").Load();
...抛出一个异常(...不允许有虚线路径......)。
... throws an exception ("...no dotted paths allowed...").
我发现工作的唯一一件事就是明确地加载孙子
在一个循环:
The only thing which I found working is to explicitely load the Grandchildren
in a loop:
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();
我想知道如果我错过了什么,如果有一些其他的方式来明确地加载孙子
在一个往返。
感谢您提前反馈!
推荐答案
正如我指出的评论,你可以尝试让查询的关系,再加入包括并执行装载。是这样的:
As I pointed in the comment you can try to get query for relation first, then add includes and execute loading. Something like:
context.Entry(parent)
.Collection(p => p.Children)
.Query()
.Include(c => c.Grandchildren) // I'm not sure if you can include grandchild directly
.Load();
这篇关于孙子藏品在EF 4.1明确加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!