简体   繁体   中英

Linq groupby with joining table

Let's suppose there is a database to manage students. I'm using the following (simplified) classes:

Student
int id
string name

StudentEnrollmentInfo
int studentId
int courseId

Course
int courseInfo
string name

In the aforementioned tables, studentenrollmentinfo is a joining table, to handle the many to many relation between courses and students.
Now I'd like to query the names of all students who are currently enrolled in a list of different courses. For example:

Get all students enrolled in Biology, Maths and Arts, I'd like to get all students that are enrolled in ALL of those classes.

I have tried the following:

List<string> requiredCourses = new List<string>(){"Maths", "Biology", "Arts"}; 

var query = from student in _context.students
join enrollmentInfo in _context.StudentEnrollmentInfo on 
    student.id equals enrollmentInfo.studentId
join course in _context.Course on course.id equals enrollmentInfo.courseId
where requiredCourses.All(r => r.equals(course.name))
select(student.name)

This however does not work, my guess is because the joins, in addition to the joining table flattens the list, making it where every student with every course combination is a unique value, making it so that there is never any AND condition that is true.

Can anyone suggest something to point me in the right direction?

List requiredCourses = new List() { "Maths", "Biology", "Arts" }; var query = (from student in _context.students join enrollmentInfo in _context.StudentEnrollmentInfo on student.id equals enrollmentInfo.studentId join course in _context.Course on course.id equals enrollmentInfo.courseId where requiredCourses.Contains(course.name) select student.name).Distinct().ToList()

hope it will solve your purpose. distinct will help for your unique data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM