【问题标题】:How to do left joins in LINQ on multiple fields in single join如何在 LINQ 中对单个连接中的多个字段进行左连接
【发布时间】:2015-05-22 16:53:31
【问题描述】:

我正在尝试对 LINQ 执行这个简单的 sql 查询。但它给了我错误。

这是需要转换为 LINQ 的 SQL 查询

 DECLARE @groupID int
 SET @groupID = 2
 SELECT * 
    FROM dbo.Person p
    LEFT JOIN dbo.PersonGroup pg ON ( p.PersonID = pg.PersonID AND pg.GroupID = @groupID)

忽略@groupID。它将作为 LINQ 查询的函数参数提供。

这是我尝试过的 LINQ 查询。

from p in Person
 join pg in PersonGroup on new { p.PersonID, groupID } equals new { pg.PersonID, pg.GroupID } into t
 from rt in t.DefaultIfEmpty()

其中 groupID 作为函数参数提供。 GroupID 和 PersonID 都是 int。但它给了我以下错误,

Error   2   The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'GroupJoin'.

我们将不胜感激。

【问题讨论】:

    标签: c# linq left-join sql-to-linq-conversion


    【解决方案1】:

    你的代码

    from p in Person
     join pg in PersonGroup on new { p.PersonID, groupID } equals new { pg.PersonID, pg.GroupID } into t
     from rt in t.DefaultIfEmpty()
    

    改成

    from p in Person
     join pg in PersonGroup on new { Person = p.PersonID, Group = groupID } equals new { Person = pg.PersonID, Group = pg.GroupID } into t
     from rt in t.DefaultIfEmpty()
    

    这样它将使用匿名类型加入

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多