【问题标题】:How can l get a total sum from one table if it is linked with a lot of tables using linq?如果使用 linq 与许多表链接,我如何从一个表中获取总和?
【发布时间】:2022-01-17 09:54:15
【问题描述】:
我有多个表,其中包含一对可能的关系,例如 Country -> Region -> Center -> Greater ->Section。该部分有一个人口普查栏。我正在尝试为我的观点编写一个 linq 查询,以获取按国家/地区分组的总人口普查。 l 还需要知道一个国家有多少个地区,有多少个中心,有多少个大区和总人口普查。它们可以是单独的查询没有问题。
【问题讨论】:
标签:
model-view-controller
entity-framework-core
【解决方案1】:
在这种情况下,LINQ 中的 SelectMany 方法是您的朋友。每个国家都有地区的集合,对吧?您可以使用 .SelectMany 将来自多个国家/地区的所有区域组合成一个区域集合。然后您需要从所有区域获取中心的集合,依此类推。
考虑这段代码:
context.Countries.SelectMany(country => country.Regions)
.SelectMany(region => region.Centers)
.SelectMany(center => center.Greaters)
.SelectMany(greater => greater.Sections)
.GroupBy(country => country.Id)
.Sum(section => section.Census);