将SQL查询转换为LINQ C#
SELECT ts.TeacherId, count(Distinct ts.SubjectId) as Subjects
from dbo.TeacherSubjects ts
GROUP BY ts.TeacherId
HAVING ts.TeacherId = 2352
这是我的LINQ查询
var SubjectsGroup = db.TeacherSubjects.Where(p => p.TeacherId == 2352).Distinct().GroupBy(x => x.TeacherId);
答案 0 :(得分:0)
var teacherId = ; // your teacherId here
var result = new {
TeacherId = teacherId,
Subjects = db.TeacherSubjects.Where(ts => ts.TeacherId == teacherId).Select(x => x.SubjectId).Distinct().Count()
};
或者您可以按SubjectId
分组:
var teacherId = ; // put your teacherId here
var result =
(from ts in TeacherSubjects.Where(x => x.TeacherId == teacherId)
group ts by ts.SubjectId into gr
select new
{
TeacherId = teacherId,
Subjects = gr.Count()
}).ToList();