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

一个人想着一个人 提交于 2019-12-22 04:37:27

问题


I am trying to do this simple sql query to LINQ. But its give me error.

Here is the SQL query that need to conver to LINQ

 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. which will be provided as function parameter for LINQ query.

Here is LINQ query what i have tried.

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. Both GroupID and PersonID are 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.


回答1:


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



来源:https://stackoverflow.com/questions/30402063/how-to-do-left-joins-in-linq-on-multiple-fields-in-single-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!