Linq包括在嵌套组中,通过查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linq包括在嵌套组中,通过查询相关的知识,希望对你有一定的参考价值。
我有一个比较复杂的查询,下面有几个嵌套的分组查询。问题是,我不知道如何在任何一个group by查询中添加includes。有没有办法在EF6中的子组查询中包含子属性?
return db.PatientOrders
.Include(x => x.Patient) // this has no effect
.Where(x => !x.ProcessedOn.HasValue && x.Patient.Home.PharmacyId == pharmacyID)
.GroupBy(x => x.Patient.Home)
.ToDictionary(x => x.Key, x => x
.ToList()
.GroupBy(y => y.Patient.Department)
.ToDictionary(y => y.Key, y => y
.Include(x => x.OrderLines) // this does not compile
.ToList()
.GroupBy(z => z.Patient)
.ToDictionary(z => z.Key, z => z.ToList(), new PatientEqualityComparer()), new HomeDepartmentEqualityComparer()), new HomeEqualityComparer());
答案
我想出了一个办法,但是我不知道这个办法在性能上有没有什么好的效果。
// group by reshapes query so previous includes are lost
// solution: flatten after group by then do includes then group by again
return db.PatientOrders
.GroupBy(x => x.Patient.Home) // Group
.SelectMany(g => g.AsEnumerable()) // Ungroup
.Include(x => x.Patient)
.Include(x => x.Patient.Home)
.Include(x => x.Patient.Doctor)
.Include(x => x.Patient.Department)
.Include(x => x.OrderLines)
.Include(x => x.OrderLines.Select(y => y.Product))
.Where(x => !x.ProcessedOn.HasValue && x.Patient.Home.PharmacyId == pharmacyID)
.AsEnumerable() // Switch to LINQ to Objects
.GroupBy(x => x.Patient.Home) // Group again
.ToDictionary(x => x.Key, x => x
.ToList()
.GroupBy(y => y.Patient.Department)
.ToDictionary(y => y.Key, y => y
.ToList()
.GroupBy(z => z.Patient)
.ToDictionary(z => z.Key, z => z.ToList(), new PatientEqualityComparer()), new HomeDepartmentEqualityComparer()), new HomeEqualityComparer());
以上是关于Linq包括在嵌套组中,通过查询的主要内容,如果未能解决你的问题,请参考以下文章
EF Core 嵌套 Linq 选择导致 N + 1 个 SQL 查询
CSharp使用另一个列表及其嵌套列表过滤带有LINQ查询的列表