Include()方法适用于对象上的list。但如果我需要深入两层呢?例如,下面的方法将返回包含如下所示属性的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))

确保使用System.Data.Entity添加;来获取包含lambda的Include版本。


EF Core

使用新的方法ThenInclude

using Microsoft.EntityFrameworkCore;

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

其他回答

让我清楚地说明一下,你可以使用字符串重载来包含嵌套的级别,而不管对应关系的多样性,如果你不介意使用字符串字面量:

query.Include("Collection.Property")

EF Core:使用“ThenInclude”加载多个级别: 例如:

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
        .ThenInclude(author => author.Photo)
    .ToList();

对于 EF 6

using System.Data.Entity;

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

确保使用System.Data.Entity添加;来获取包含lambda的Include版本。


EF Core

使用新的方法ThenInclude

using Microsoft.EntityFrameworkCore;

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

我有一个索引页面,显示MbsNavigation。作为外键加载的固件对象的名称。固件对象很大,因此通过Internet加载索引页需要几分钟。

BatterySystem = await _context.BatterySystems.Include(b => b.MbsNavigation)

这是一个加载固件的解决方案。名字只有:

BatterySystem = await _context.BatterySystems
.Include(b => b.MbsNavigation)
.Select(b => new BatterySystem() 
{
    Name = b.Name,
    MbsNavigation = new Firmware() { Name = b.MbsNavigation.Name },
})
.ToListAsync();

现在索引立即加载。

我还必须使用多个包含,在第三层,我需要多个属性

(from e in context.JobCategorySet
                      where e.Id == id &&
                            e.AgencyId == agencyId
                      select e)
                      .Include(x => x.JobCategorySkillDetails)
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.DurationType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RuleType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RateType))
                      .FirstOrDefaultAsync();

这可能会帮助到某些人:)