Linq包括在嵌套组中,通过查询

问题描述 投票:1回答:1

我有一个比较复杂的查询,下面有几个嵌套的分组查询。问题是,我不知道如何在任何一个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());
c# .net entity-framework linq entity-framework-6
1个回答
0
投票

我想出了一个办法,但是我不知道这个办法在性能上有没有什么好的效果。

            // 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());
© www.soinside.com 2019 - 2024. All rights reserved.