I have an issue I want to translate this SQL query int asp.net. there is a relationship between student table and teacher table many to many and I want to display students that have more than one teacher
x
select COUNT(StudentId), StudentId from StudentTeachers
group by StudentId
having COUNT(StudentId)> 1
and that what I trying to do in asp.net
var data = db.StudentTeachers.
Join(db.Students, a => a.StudentId, b => b.ID, (a, b) =>a).GroupBy(x=> x.StudentId);
Advertisement
Answer
You can try out both ways.
Using Lambda Expressions
db.StudentTeachers.GroupBy(s => s.StudentId)
.Where(grp => grp.Count() > 1)
.Select(grp => new
{
StudentCount = grp.Count(),
StudentId = grp.Key
}).ToList();
Using SQL like query expressions
from s in db.StudentTeachers
group s by s.StudentId into grp
where grp.Count() > 1
select new { StudentId = grp.Key, StudentCount = grp.Count() }).ToList();