在LINQ中获取内部联接和分组的结果

时间:2015-06-04 09:36:05

标签: linq entity-framework linqpad

我正在努力分组,基本上我需要获得所有教师的名单以及他们在所有班级中负责的学生总数。我需要使用Linq表达式

这是ER图 enter image description here

LINQ

from _teacher in Teachers
join _class in Classes on _teacher.Id equals _class.TeacherId 
join _studentClasses in StudentClasses on _class.Id equals _studentClasses.ClassId 
group _studentClasses by _studentClasses.StudentId into _grouped 
select new {_teacher, _class.Name, _studentClasses.StudentId}

1 个答案:

答案 0 :(得分:1)

您只能使用已分组的列。所以我认为你可以这样做:

from _teacher in Teachers
join _class in Classes 
    on _teacher.Id equals _class.TeacherId 
join _studentClasses in StudentClasses 
    on _class.Id equals _studentClasses.ClassId 
group _studentClasses by 
new
{
   TeacherName=__teacher.Name,
   ClassName=_class.Name
} 
into _grouped 
select new 
{
    _grouped.Key.TeacherName, 
    _grouped.Key.ClassName, 
    stundetCount=_grouped.Count()
}