将SQL查询转换为linq C#

时间:2019-06-11 19:00:04

标签: c# linq sql-to-linq-conversion

将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);

1 个答案:

答案 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();