entity framework – 包含多级属性

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;添加using System.Data.Entity; 获取Include lambda的版本。


如果您使用EF Core,则可以使用新方法ThenInclude

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

如果我正确理解你,你正在问包括嵌套的属性。 如果是这样 :

 .Include(x => x.ApplicationsWithOverrideGroup.NestedProp) 

要么

 .Include("ApplicationsWithOverrideGroup.NestedProp") 

要么

 .Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}") 

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

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

我为entity framework6(。核心风格)做了一个小帮手,以一种很好的方式包含子实体。

现在在NuGet上:Install-Package ThenInclude.EF6

 using System.Data.Entity; var thenInclude = context.One.Include(x => x.Twoes) .ThenInclude(x=> x.Threes) .ThenInclude(x=> x.Fours) .ThenInclude(x=> x.Fives) .ThenInclude(x => x.Sixes) .Include(x=> x.Other) .ToList(); 

我也不得不使用多个包含,在第三级我需要多个属性

 (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(); 

这可能有助于某人:)