简体   繁体   English

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

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

I am trying to do this simple sql query to LINQ. 我正在尝试对LINQ执行这个简单的SQL查询。 But its give me error. 但它给我错误。

Here is the SQL query that need to conver to LINQ 这是需要转换为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)

Ignore @groupID. 忽略@groupID。 which will be provided as function parameter for LINQ query. 它将作为LINQ查询的函数参数提供。

Here is LINQ query what i have tried. 这是我试过的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()

Where groupID is provided as function parameter. 其中groupID作为函数参数提供。 Both GroupID and PersonID are int. GroupID和PersonID都是int。 But it gives me following error, 但它给了我以下错误,

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

Little help would be appreciated. 很少的帮助将不胜感激。

Your Code 你的守则

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

Change it to 将其更改为

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

That way it will join using the Anonymous type 这样它将使用匿名类型加入

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

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