EF Core 左连接计数

Posted

技术标签:

【中文标题】EF Core 左连接计数【英文标题】:EF Core left join with count 【发布时间】:2018-07-09 08:18:33 【问题描述】:

我在 mysql 数据库上有 3 个表。我想在这 3 个表之间进行左连接并按分组计数。

城市表 身份证 名称 学校表 身份证 城市编号 名称 学生桌 身份证 学校编号 姓名

/* MySql raw query like this: */
select Count(tstudent.id) as StudentCount, tcity.Id, tcity.Name
from City tcity
left join School tschool on tcity.Id = tschool.CityId
left join Student tstudent on tschool.Id = tstudent.SchoolId
group by tcity.Id;

使用 EF Core 我尝试这样:

class CityWithStudentCount 
    public int Id  get;set; 
    public string CityName  get;set; 
    public int StudentCount  get;set; 

Ef Core:

var db = new MyDbContext();

var result = (from city in db.City
             join school in db.School on city.Id equals school.CityId into tcity
             from r1 in tcity.DefaultIfEmpty()

             join student in db.Student on school.Id equals student.SchoolId into tschool
             from r2 in tschool.DefaultIfEmpty()
             
             select new CityWithStudentCount
             
                 Id = city.Id,
                 CityName = city.Name,
                 StudentCount = tschool.count()
              into s1
             
             group s1 by s1.Id)
             .Select(s=>s.ToList())
             .ToList();

结果一定是这样的:

1 City1 10
2 City2 3
3 City3 0
4 City4 0
5 City5 12

我如何使用 Entity Framework Core 对这个结果进行这样的查询。谢谢。

【问题讨论】:

使用city.Schools 【参考方案1】:

您的查询错误。

 var result = (from city in db.City
         join school in db.School on city.Id equals school.CityId into t1
         from school in t1.DefaultIfEmpty()

         join student in db.Student on school.Id equals student.SchoolId into t2
         from student in t2.DefaultIfEmpty()

         group student by new  city.Id,city.Name  into cityGrouped
         select new CityWithStudentCount
         
             Id = cityGrouped.Key.Id,
             CityName = cityGrouped.Key.Name,
             StudentCount = cityGrouped.Count(x => x.student != null)
         
         .ToList();

另外,我强烈建议您使用导航属性而不是手动构建连接。

【讨论】:

这可以是group student by,因为您不需要city 来进行计数。 您可以从您在byinto 之间定义的键中获取这些信息。 是的,你是对的。谢谢提醒。我更新了答案。 @ASPMaker 这个答案已根据我的建议进行了更新。您唯一可以做的其他可能的事情是使用导航属性而不是连接(如果您设置了它们)。类似from school in city.Schools.DefaultIfEmpty() @ASPMaker,查询有问题吗?

以上是关于EF Core 左连接计数的主要内容,如果未能解决你的问题,请参考以下文章

LINQ EF Core 左连接 [重复]

如何在 EF / EF Core 中的第二个表上实现具有某些条件的左连接?

如何在 EF 中指定左连接?

EF的左连接查询

左连接的 SQL 计数

Clickhouse 数组连接与左连接和计算计数