繁体   English   中英

如何在LINQ中在单个连接中的多个字段上进行左连接

[英]How to do left joins in LINQ on multiple fields in single join

我正在尝试对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'.

很少的帮助将不胜感激。

你的守则

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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM