EF Core离开加入计数

时间:2018-01-30 12:30:49

标签: c# mysql entity-framework .net-core linq-to-entities

我在MySql数据库上有3个表。我想在这3张桌子之间做左联,并用group by计算。

城市表
标识
名称

学校表
标识
CityId
名称

学生表
标识
SchoolId
名称

**MySql raw query like this:**
Select Count(t3.id) as StudentCount, t1.Id, t1.Name from City t1
Left Join School t2 ON(t1.Id=t2.CityId)
Left Join Student(t2.Id=t3.SchoolId)
Group By t1.Id;

使用EF Core我会尝试这样:

***Complex 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 t1
             from r1 in t1.DefaultIfEmpty()

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

             select new CityWithStudentCount
             {
                 Id = city.Id,
                 CityName = city.Name,
                 StudentCount = t2.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为此结果执行此查询。谢谢。

1 个答案:

答案 0 :(得分: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();

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