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
包含所有Children
的Parent
并且孙子
一步到位:
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< 的字符串重载/code> ...
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
一次往返。
感谢您的提前反馈!
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; }
}
... 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))
Is something similar possible for explicit loading?
The child collection can be explicitely loaded this way:
Parent parent = context.Parents.Find(parentId);
context.Entry(parent).Collection(p => p.Children).Load();
But trying to load the children in a similar way as with Include
...
context.Entry(parent)
.Collection(p => p.Children.Select(c => c.Grandchildren)).Load();
... doesn't compile und the string overload of Collection
...
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();
I am wondering if I missed something and if there is some other way to explicitely load the GrandChildren
in one roundtrip.
Thanks for feedback in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如我在评论中指出的,您可以尝试首先获取关系查询,然后添加包含并执行加载。像这样的东西:
As I pointed in the comment you can try to get query for relation first, then add includes and execute loading. Something like: