4

我有 3 个课程并试图用来LINQ methods执行一个INNER JOIN和一个LEFT JOIN. 我能够分别执行每个,但没有运气在一起,因为我什至无法弄清楚语法。

最终,我要编写的 SQL 将是:

SELECT *
FROM [Group] AS [g]
INNER JOIN [Section] AS [s] ON [s].[GroupId] = [g].[Id]
LEFT OUTER JOIN [Course] AS [c] ON [c].[SectionId] = [s].[Id]

课程

public class Group {
    public int Id { get; set; }
    public int Name { get; set; }
    public bool IsActive { get; set; }
    public ICollection<Section> Sections { get; set; }
}

public class Section {
    public int Id { get; set; }
    public int Name { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }
    public bool IsActive { get; set; }
    public ICollection<Course> Courses { get; set; }
}

public class Course {
    public int Id { get; set; }
    public int UserId { get; set; }
    public int Name { get; set; }
    public int SectionId { get; set; }
    public bool IsActive { get; set; }
}

样品

我希望结果是 type Group。我成功地执行了LEFT JOINbetween Sectionand Course,但是我有一个IQueryable<a> , which is not what I want, sinceGroup` 类型的对象。

var result = db.Section
               .GroupJoin(db.Course, 
                    s => s.Id,
                    c => c.SectionId,
                    (s, c) => new { s, c = c.DefaultIfEmpty() })
               .SelectMany(s => s.c.Select(c => new { s = s.s, c }));

我也试过这个,但返回NULL是因为它INNER JOIN在所有表上执行,并且用户没有输入任何Courses.

var result = db.Groups
               .Where(g => g.IsActive)
               .Include(g => g.Sections)
               .Include(g => g.Sections.Select(s => s.Courses))
               .Where(g => g.Sections.Any(s => s.IsActive && s.Courses.Any(c => c.UserId == _userId && c.IsActive)))
               .ToList();

问题

如何以最少的数据库调用次数执行 anINNER和 a并获得 type 的结果?LEFT JOINGroup

期望的结果

我想有 1 个类型的对象Group,但只要 aGroup有一个Section. 我还想返回Courses用户拥有的特定Section或 return NULL

4

3 回答 3

2

用于DefaultIfEmpty执行外部左连接

from g in db.group
join s in db.section on g.Id equals s.GroupId 
join c in db.course on c.SectionId equals s.Id into courseGroup
from cg in courseGroup.DefaultIfEmpty()
select new { g, s, c }; 
于 2018-07-18T20:14:35.493 回答
2

我认为如果不返回新的(匿名)对象而不是Group(如this answer所示),您所要求的是不可能的。由于关系和实体缓存的工作方式, EF 不允许您在 a 中获取过滤的Course集合Section,这意味着您不能为此任务使用导航属性。

首先,您想控制加载哪些相关实体,因此我建议通过将SectionsCourses集合属性标记为virtual实体中的属性来启用延迟加载(除非您已为应用程序中的所有实体启用延迟加载),因为我们不希望 EF 加载相关的SectionsCourses因为无论如何它都会为每个用户加载所有课程。

public class Group {
    public int Id { get; set; }
    public int Name { get; set; }
    public bool IsActive { get; set; }
    public virtual ICollection<Section> Sections { get; set; }
}

public class Section {
    public int Id { get; set; }
    public int Name { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }
    public bool IsActive { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

在方法语法中,查询可能看起来像这样:

var results = db.Group
    .Where(g => g.IsActive)
    .GroupJoin(
        db.Section.Where(s => s.IsActive),
        g => g.Id,
        s => s.GroupId,
        (g, s) => new
        {
            Group = g,
            UserSections = s
                .GroupJoin(
                    db.Course.Where(c => c.IsActive && c.UserId == _userId).DefaultIfEmpty(),
                    ss => ss.Id,
                    cc => cc.SectionId,
                    (ss, cc) => new
                    {
                        Section = ss,
                        UserCourses = cc
                    }
                )
        })
    .ToList();

你会将结果消耗为:

foreach (var result in results)
{
    var group = result.Group;

    foreach (var userSection in result.UserSections)
    {
        var section = userSection.Section;

        var userCourses = userSection.UserCourses;

    }
}

现在,如果您不需要在数据库级别对组结果进行额外过滤,您也可以使用此 LINQ 查询来使用 INNER JOIN 和 LEFT OUTER JOIN 方法并在内存中进行分组:

var results = db.Group
    .Where(g => g.IsActive)
    .Join(
        db.Section.Where(s => s.IsActive),
        g => g.Id,
        s => s.GroupId,
        (g, s) => new
        {
            Group = g,
            UserSection = new
            {
                Section = s,
                UserCourses = db.Course.Where(c => c.IsActive && c.UserId == _userId && c.SectionId == s.Id).DefaultIfEmpty()
            }
        })
    .ToList() // Data gets fetched from database at this point
    .GroupBy(x => x.Group) // In-memory grouping
    .Select(x => new
    {
        Group = x.Key,
        UserSections = x.Select(us => new
        {
            Section = us.UserSection,
            UserCourses = us.UserSection.UserCourses
        })
    });

请记住,每当您尝试访问group.Sectionssection.Courses时,您将触发延迟加载,这将获取所有子部分或课程,无论_userId.

于 2018-07-18T22:12:31.487 回答
1

您的 SQL 的类型不是 [Group] (类型组将是:select [Group].* from ...),无论如何,如果您想要这样,那么它的简单形式将是:

var result = db.Groups.Where( g => g.Sections.Any() );

但是,如果你真的想转换你的 SQL,那么:

var result = from g in db.Groups
             from s in g.Sections
             from c in s.Courses.DefaultIfEmpty()
             select new {...};

即使这样也可以:

var result = from g in db.Groups
             select new {...};

提示:在一个设计良好的关系数据库中,您很少需要使用 join 关键字。而是使用导航属性。

于 2018-07-18T20:18:10.387 回答