gpt4 book ai didi

.net - 在EF 4.1中显式加载孙子集合

转载 作者:行者123 更新时间:2023-12-03 11:42:18 25 4
gpt4 key购买 nike

给定以下模型...

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加载和包含所有 ParentChildrenGrandchildren,如下所示:
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

感谢您的提前反馈!

最佳答案

正如我在评论中指出的那样,您可以尝试首先获取有关关系的查询,然后添加包含并执行加载。就像是:

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

关于.net - 在EF 4.1中显式加载孙子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5966994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com