c# - Entity Framework - 包括多个级别的属性

标签 c# entity-framework eager-loading

Include() 方法非常适用于对象列表。但是,如果我需要深入两层怎么办?例如,下面的方法将返回具有此处显示的包含属性的 ApplicationServers。但是,ApplicationsWithOverrideGroup 是另一个包含其他复杂对象的容器。我也可以对该属性执行 Include() 吗?或者我怎样才能让该属性完全加载?

就目前而言,这个方法:

public IEnumerable<ApplicationServer> GetAll()
{
    return this.Database.ApplicationServers
        .Include(x => x.ApplicationsWithOverrideGroup)                
        .Include(x => x.ApplicationWithGroupToForceInstallList)
        .Include(x => x.CustomVariableGroups)                
        .ToList();
}

将仅填充 Enabled 属性(下方),而不填充 Application 或 CustomVariableGroup 属性(下方)。我该如何做到这一点?

public class ApplicationWithOverrideVariableGroup : EntityBase
{
    public bool Enabled { get; set; }
    public Application Application { get; set; }
    public CustomVariableGroup CustomVariableGroup { get; set; }
}

最佳答案

对于 EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

确保添加 using System.Data.Entity; 以获取接受 lambda 的 Include 版本。


对于 EF 核心

使用新方法ThenInclude

using Microsoft.EntityFrameworkCore;

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

关于c# - Entity Framework - 包括多个级别的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822656/

相关文章:

c# - 使用 Newtonsoft Json.Net 反序列化为 IEnumerable 类

c# - 如何根据另一个属性的选择异步更新 viewmodel 属性

c# - EF Core 3 未加载第二层或更深层的相关数据

php - 来自 hasMany 关系的 Laravel 预加载模型

node.js - 在 where 子句中对 hasMany 关联的属性进行后续过滤

c# - 我的数据绑定(bind)有什么问题?

c# - 使用项目依赖项作为全局命令运行 Dnx 控制台应用程序

c# - 如何在 Entity Framework 6 中混合使用 TPH 和 TPT?

c# - 自动化 EF 迁移 "Update-Database -Script"

entity-framework - 当我有一个多态集合时,如何在 Entity Framework 4.3 中进行多级预加载?