我使用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)...
等等?
答案 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();
}