【问题标题】:EF Core querying many-to-many relationship tablesEF Core 查询多对多关系表
【发布时间】:2020-01-02 21:45:32
【问题描述】:

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

例如 StudentsCourses 是主表,而 Enrollment(存储 StudentID、CourseID)是连接表。

给定 5 门课程的列表,如何在 EF Core 中找到恰好注册了这 5 门课程的学生?

【问题讨论】:

  • 如果有人在寻找答案,请参阅下面对我有用的链接。 stackoverflow.com/questions/59621091/…>

标签: entity-framework many-to-many


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-01-19
    • 1970-01-01
    • 2021-10-21
    • 2017-11-13
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多