我有 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 JOIN
between Section
and Course
,但是我有一个IQueryable<
a> , which is not what I want, since
Group` 类型的对象。
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 JOIN
Group
期望的结果
我想有 1 个类型的对象Group
,但只要 aGroup
有一个Section
. 我还想返回Courses
用户拥有的特定Section
或 return NULL
。