在实体框架中使用lambda语法进行多个左联接

时间:2019-05-29 19:16:23

标签: entity-framework entity-framework-core

我有以下3张桌子

课程

Id, SortOrder, CourseName, CourseArea, CourseFor

学生

Id, FullName

课程学生

CourseId, StudentId, CollegeId

要求:

从“医疗”区域为“ 125”学院的“外国”学生提供所有课程的学生。即使没有学生注册,也要包含课程。

有效的SQL查询:

SELECT cr.Id, cr.CourseName, st.FullName
FROM dbo.Courses cr
LEFT JOIN dbo.CourseStudents cst ON cr.Id = cst.CourseId 
                                 AND cst.CollegeId = 125
LEFT JOIN dbo.Students st ON cst.StudentId = st.Id
WHERE 
    cr.CourseArea = 'Medical'
    AND cr.CourseFor = 'Foreigner'
ORDER BY 
    cr.SortOrder, st.FullName

有人可以用lambda语法(我尝试过GroupJoin来帮助我)吗?虽然我正在寻找的是lambda语法,但查询语法也很不错。

更新:我距离很近,但还不完整

    context.Courses
        .GroupJoin(context.CourseStudents,
            x => new { x.Id, CollegeId NOT IN COURSES TABLE :( },
            y => new { Id = y.CourseId, y.CollegeId=125 },
            (x, y) => new { Courses = x, CourseStudents = y })
        .SelectMany(x => x.CourseStudents.DefaultIfEmpty(),
            (x, y) => new { x.Courses, CourseStudents = y })
        .GroupJoin(context.Students,
            x => x.CourseStudents.StudentId,
            y => y.Id,
            (x, y) => new { CoursesCourseStudents = x, Students = y }
        )
        .SelectMany(x => x.Students.DefaultIfEmpty(),
        (x, y) => new { x = x.CoursesCourseStudents, Students = y })
        .Select(x => new
        {
            x.x.Courses.Id,
            x.x.Courses.CourseName,
            x.Students.FullName,
            x.x.CourseStudents.CollegeId,
            x.x.Courses.CourseFor,
            x.x.Courses.CourseArea,
            x.x.Courses.SortOrder
        })
        .Where(x => x.CourseFor == "Foreigner" && x.CourseArea == "Medical")
        .OrderBy(x => x.SortOrder)
        .ToList();

1 个答案:

答案 0 :(得分:0)

解决方案:我通过执行以下操作使其正常运行。参见第3行和第4行。

context.Courses
    .GroupJoin(context.CourseStudents,
        x => new { x.Id, CollegeId=125 },
        y => new { Id = y.CourseId, y.CollegeId },
        (x, y) => new { Courses = x, CourseStudents = y })
    .SelectMany(x => x.CourseStudents.DefaultIfEmpty(),
        (x, y) => new { x.Courses, CourseStudents = y })
    .GroupJoin(context.Students,
        x => x.CourseStudents.StudentId,
        y => y.Id,
        (x, y) => new { CoursesCourseStudents = x, Students = y }
    )
    .SelectMany(x => x.Students.DefaultIfEmpty(),
    (x, y) => new { x = x.CoursesCourseStudents, Students = y })
    .Select(x => new
    {
        x.x.Courses.Id,
        x.x.Courses.CourseName,
        x.Students.FullName,
        x.x.CourseStudents.CollegeId,
        x.x.Courses.CourseFor,
        x.x.Courses.CourseArea,
        x.x.Courses.SortOrder
    })
    .Where(x => x.CourseFor == "Foreigner" && x.CourseArea == "Medical")
    .OrderBy(x => x.SortOrder)
    .ToList();