Lets say that I have following tables:
Student(id(pk), name)
Class(id(pk), name)
StudentClass(id(pk), studentId(fk), classId(fk))
Imagine as follows:
Student
table contains:
(1,"John"), (2, "Mike"), (3,"Josh")
Class
table contains:
(1,"Geography"), (2, "Math")
StudentClass
table contains:
(`1, 1, 1),(2,2,2),(3,3,2)
Lets now assume that I have a StudentClassDTO
class which contains
List<string> StudentNames
string ClassName
How can I by using using LINQ query get data into StudentClassDTO
? Any help appreciated.
var data = from sc in context.GetStudentClasses
join s in context.GetStudents on sc.StudentId equals s.Id
join c in context.GetClass on sc.ClassId equals c.Id
select new StudentClassDTO
{
}
so it gets name and classname 3 seperate ones but I need if their classes are same it should have to combine them where it will be just one classname and 2 different students. So it should be like {john, Geography} and {[Mike, Josh], Math}
Solution
from c in classes
join sc in studentClasses on c.Id equals sc.ClassId
join s in student on sc.StudentId equals s.StudentId
group s by new {c.Name} into g
select new StudentClassDTO
{
ClassName = g.Key.Name,
StudentNames = g.Select(a=>a.Name).ToList()
};