How to make left joins in LINQ for multiple fields in one join

I am trying to make this simple SQL LINQ query. But that gives me an error.

Here is the SQL query to convert 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 a function parameter for the LINQ query.

Here is the LINQ query that I 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 a function parameter. Both GroupID and PersonID are int. But this gives me the 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'. 

A little help would be appreciated.

+5
source share
1 answer

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

This way it will be used using an anonymous type

+6
source

All Articles