【问题标题】:How do you perform a left outer join with a where clause using linq lambda extension methods如何使用 linq lambda 扩展方法执行带有 where 子句的左外连接
【发布时间】:2019-11-08 21:04:39
【问题描述】:

我在 sql 中有以下代码,我想进行 linq lambda 查询。有没有办法做到这一点?

SELECT *
FROM dbo.Idea i
    LEFT OUTER JOIN dbo.IdeaCollaborator ic
        ON ic.Idea_Id = i.Id
WHERE i.Submitter_Id = 'Peter'
      OR ic.User_Id = 'Peter';

我参考How do you perform a left outer join using linq extension methods

得到

db.Ideas
 .GroupJoin(
   db.IdeaCollaborators,
   i => i.Id,
   ic => ic.Idea_Id,
   (x, y) => new { Ideas = x, IdeaCollaborators = y })
 .SelectMany(
   x => x.IdeaCollaborators.DefaultIfEmpty(),
   (x, y) => new
   { x.Ideas.Id, x.Ideas.IdeaStatus_Id, y.User_Id}
 )

但我被卡住了

【问题讨论】:

    标签: sql linq lambda left-join where-clause


    【解决方案1】:

    答案是在 where 的关系中使用 .FirstOrDefault(),因为在关系中 FirstOrDefault 与我们将从 select 中获取的项目相同,因此适用于 where 子句

    db.Ideas
     .GroupJoin(
      db.IdeaCollaborators,
      i => i.Id,
      ic => ic.Idea_Id,
      (x, y) => new { Ideas = x, IdeaCollaborators = y })
     .Where(gj => gj.Ideas.Submitter_Id == "Peter" | gj.IdeaCollaborators.FirstOrDefault().User_Id == "Peter")
     .SelectMany(
      x => x.IdeaCollaborators.DefaultIfEmpty(),
      (x, y) => new
      { x.Ideas.Id, x.Ideas.IdeaStatus_Id, y.User_Id })
    );
    

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多