如何使用linq lambda扩展方法使用where子句执行左外部联接

时间:2019-06-26 21:08:32

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

我在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}
 )

但是我被困住了

1 个答案:

答案 0 :(得分:0)

答案是在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 })
);