EF - 可以使用单个.Include()加载子属性的属性吗?

时间:2018-03-08 03:44:29

标签: c# entity-framework

我使用EF连接到SQL Server(C#)。我可以使用以下代码获得所需的结果列表:

using (var context = new DbContext())
{
    var list = context.Jobs
        .Include(a => a.JobDetails)
        .Include(a => a.Shifts.Select(b => b.ShiftDetails.Select(c => c.FirstProperty))) // !!
        .Include(a => a.Shifts.Select(b => b.ShiftDetails.Select(c => c.SecondProperty))) // !!
        .Include(a => a.Shifts.Select(b => b.ShiftDetails.Select(c => c.ThirdProperty))) // !!
        .Include(a => a.Shifts.Select(b => b.ShiftDetails.Select(c => c.FourthProperty))) // !!
        .ToListAsync();
}

在这里,单个包括每个属性直到第三级似乎是可疑的。有什么方法可以简化它,这有点像:

.Include(a => a.Shifts.Select(b => b.ShiftDetails).Select(c => c.FirstProperty, c.SecondProperty, c.ThirdProperty)...

等等?

1 个答案:

答案 0 :(得分:0)

我已经提出了两个解决方案。 Solution 1与您要实现的目标相关,Solution 2是一种更优化的方式,因为您已经设计了正确的数据库架构

解决方案1 ​​

using (var context = new DbContext())
{
    var list = context.Jobs
        .Include(a => a.JobDetails)
        .Include(a => a.Shifts.Select(b => b.ShiftDetails.Select(c => new {c.FirstProperty,c.SecondProperty,c.ThirdProperty,c.FourthProperty})))
        .ToListAsync();
}

解决方案2

using (var context = new DbContext())
{
    var list = context.Jobs
        .Include(a => a.JobDetails)
        .Include(a => a.Shifts)
        .Include(a => a.ShiftDetails)
        .Select(a => new {a.ShiftDetails.FirstProperty, a.ShiftDetails.SecondProperty,a.ShiftDetails.ThirdProperty,a.ShiftDetails.FourthProperty})
        .ToListAsync();
}