【问题标题】:Linq includes in nested group by queryLinq 按查询包含在嵌套组中
【发布时间】:2020-04-22 16:11:58
【问题描述】:

我在下面有一个相对复杂的查询,其中包含一些嵌套的 group by 查询。问题是我不知道如何通过查询将包含添加到任何组中。有没有办法在 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】:

    我想出了一种方法,但我不确定该解决方案在性能方面是否有任何好的表现。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      相关资源
      最近更新 更多