在 Entity Framework 中,我知道您可以将属性设置为虚拟属性以使其延迟加载,这很棒。但是在我的服务代码中,我想加载一个子项列表,以及每个子项中的一个列表。
我可以加载 2 次数据,而不是让 Entity Framework 加载此数据。
这是我的类(class)的一个例子
public class Parent
{
public long Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public long Id { get; set; }
public long ParentId { get; set; }
public ICollection<GrandChild> { get; set; }
}
public class GrandChild
{
public long Id { get; set; }
public long ChildId { get; set; }
public virtual AnotherClass AnotherProperty { get; set; }
}
在我的服务代码中,我像这样加载数据,因为我看不到能够一次加载所有数据(也许我只是不知道正确的查询语法)
var parent = await _context.Parents
.Where(e => e.Id == 9)
.Include(e => e.Children)
.FirstOrDefaultAsync();
var grandchildren = await _context.GrandChildrens
.Where(e => e.Child.ParentId == 9)
.ToListAsync();
// this is load again?
foreach (var child in parent.Children)
child.GrandChildren = (from a in grandChildren where a.ChildId == child.Id).ToList();
现在每次我尝试设置 child.GrandChildren
时, Entity Framework 都会尝试加载数据。我怎样才能阻止它加载数据,但又不删除 virtual
关键字,就像在其他情况下一样,我希望 Entity Framework 延迟加载。
此外,如果有人知道如何在 1 个查询中加载父、子、孙,也请告诉我
最佳答案
我认为您可以像下面这样急切地加载相关实体:
var parent = await _context.Parents
.Where(e => e.Id == 9)
.Include(e => e.Children.GrandChildrens)
.FirstOrDefaultAsync();
这应该加载 parent 、他们的 child 和他们的孙子。
关于c# - 将属性设置为虚拟时停止加载 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32734878/