Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 434
Monirul Islam Avatar asked May 22 '15 16:05

Monirul Islam


People also ask

Can we use left join in LINQ?

A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group join.

How do multiple Left joins work?

Here when it comes to Left Join in SQL it only returns all the records or tuples or rows from left table and only those records matching from the right table. Syntax For Left Join: SELECT column names FROM table1 LEFT JOIN table2 ON table1.

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

Can we do Joins in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.


1 Answers

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

like image 155
CheGueVerra Avatar answered Sep 20 '22 04:09

CheGueVerra