【发布时间】:2018-07-19 13:11:25
【问题描述】:
我有 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; }
}
样本
我希望结果为Group 类型。我成功地在Section 和Course 之间执行了LEFT JOIN,但是我有一个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();
问题
如何以最少的数据库调用次数执行INNER 和LEFT JOIN 并获得Group 类型的结果?
期望的结果
我想要 1 个 Group 类型的对象,但前提是 Group 具有 Section。我还想返回用户对特定Section 的Courses 或返回NULL。
【问题讨论】:
标签: c# linq lambda linq-method-syntax