Множественное левое соединение с использованием лямбда-синтаксиса в Entity Framework - PullRequest
0 голосов
/ 29 мая 2019

У меня есть следующие 3 таблицы

Курсы

Id, SortOrder, CourseName, CourseArea, CourseFor

Студенты

Id, FullName

CourseStudents

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

Может кто-нибудь помочь мне с синтаксисом лямбды (я пробовал GroupJoin)? В то время как я ищу лямбда-синтаксис, синтаксис запроса также полезно знать.

ОБНОВЛЕНИЕ: Я очень близок, но все еще не завершен

    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 голосов
/ 31 мая 2019

РЕШЕНИЕ: Я заработал, выполнив следующее.Смотрите строки 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...