实体框架 - 内连接到左连接

时间:2014-04-22 14:23:53

标签: c# sql linq entity-framework join

美好的一天!我需要在我的查询中将变换连接转换为左连接 -

        var query = (from sections in context.Sections
                     join themes in context.Themes on sections.SectionId equals themes.SectionId
                     join comments in context.Comments on themes.ThemeId equals comments.ThemeId
                     select new { sections.SectionId, sections.SectionTitle, themes.ThemeId, comments.CommentId } into x
                     group x by new { x.SectionId, x.SectionTitle } into g
                     select new SectionInfo
                     {
                         SectionId = g.Key.SectionId,
                         SectionTitle = g.Key.SectionTitle,
                         ThemeCount = g.Select(s => s.ThemeId).Count(),
                         CommentCount = g.Select(s => s.CommentId).Count()
                     }).ToList();

- 拜托,我不知道(

1 个答案:

答案 0 :(得分:2)

您需要使用DefaultIfEmpty

一种方式是这样的:

from themes in context.Themes.Where(x => sections.SectionId == x.SectionId)
                             .DefaultIfEmpty()

替代方式

join themes in context.Themes on sections.SectionId equals themes.SectionId into themesGroup
from themes in themesGroup.DefaultIfEmpty()