c# - 将属性设置为虚拟时停止加载 Entity Framework

标签 c# .net entity-framework entity-framework-6

在 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/

相关文章:

C# 运算符重载 == 和 pragma 警告 660 & 661 在不相关时不覆盖 Equals 和 GetHashCode

c# - 不可变类型是否适用于此缓存问题

c# - UWP 等同于用于序列化 XAML 的 XamlWriter

c# - 为什么 HttpClientHandler 同时具有 Proxy 和 UseProxy 属性?

mysql - SQL 错误 (1231) : Variable 'optimizer_switch' can't be set to the value of 'derived_merge=OFF'

c# - 如何废弃.Net框架中现有的方法?

c# - ASP.NET API 无法在 Azure 上发布

c# - 面向对象设计/设计模式场景

.net - EntityFramework .net 4 用一个简单的方法更新实体

c# - Entity Framework 数据库优先 .Net Core