21 May 2015

Left vs right join in linq to sql

Here's how you do a left join in Linq:

var results = from tbl1 in table1
join tbl2 in table2
on tbl1.User equals tbl2.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = tbl1,
UserGrowth = j
};

If you want to do a right join, just swap the tables that you're selecting, like so:

var results = from tbl2 in table2
join tbl1 in table1
on tbl2.User equals tbl1.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = j,
UserGrowth = tbl2
};

The important part of the code is the into statement, followed by the DefaultIfEmpty. This tells Linq that we want to have the default value (i.e. null) if there isn't a matching result in the other table.


A right outer join is not possible with LINQ. LINQ only supports left outer joins. If we swap the tables and do a left outer join then we can get the behavior of a right outer join.

No comments: