Entity framework EF核心查询多对多关系表

Entity framework EF核心查询多对多关系表,entity-framework,many-to-many,Entity Framework,Many To Many,我有一个关于查询多对多关系表的问题 例如学生和课程是主表,而注册(存储StudentID,CourseID)是联接表 给出一个5门课程的列表,关于如何找到在EF Core中准确注册了这5门课程的学生?首先,您需要这样获得注册列表 var enrollments = from s in dc.Students from c in s.Courses select new { StudentID = s.StudentID

我有一个关于查询多对多关系表的问题

例如
学生
课程
是主表,而
注册
(存储StudentID,CourseID)是联接表


给出一个5门课程的列表,关于如何找到在EF Core中准确注册了这5门课程的学生?

首先,您需要这样获得注册列表

var enrollments  = from s in dc.Students
                   from c in s.Courses
                   select new { StudentID = s.StudentID, CourseID = c.CourseID };
其次,您可以按
StudentId

var groupedEnrollment = enrollments.GroupBy(p => p.StudentId)
                                            .Select(g => new 
                                            {
                                                StudentId = g.Key,
                                                Courses = g.Select(p => p.CourseId).ToArray() 
                                            });
最后,根据相应的条件选择结果

var courses = new[] { 1, 2, 3, 4, 5 };
var result = groupedEnrollment.Where(g => 
                                         g.Courses.Length == courses.Length && 
                                         g.Courses.Intersect(courses).Count() == courses.Length);       

如果有人想知道答案,请看下面的链接,它对我有用。