如何在LINQ中在单个连接中的多个字段上进行左连接
我正在尝试对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()
这样它将使用匿名类型加入