LINQ has a Join
operator, that basically translates to something like a SQL INNER JOIN. There is no built in operator for a LEFT JOIN in LINQ, but you can achieve the same result by using a combination of GroupJoin
, SelectMany
and DefaultIfEmpty
. But there is a chance that this might change in the future, as there is a proposal to add a LeftJoin
operator in .net 10.
Now in your every day life, this might not be a big deal, but when it comes to Entity Framework and LINQ to SQL, this can be a nice addition.
How to do LEFT JOINs with LINQ
This is how you would do a LEFT JOIN in LINQ:
var query =
from t1 in _dbContext.Table1
join t2 in _dbContext.Table2 on t2.Id equals t1.T2Id into joinedGroup
from joined in joinedGroup.DefaultIfEmpty()
Or if you are using the method syntax:
var query =
_dbContext.Table1
.GroupJoin(_dbContext.Table2, t1 => t1.T2Id, t2 => t2.Id, (t1, t2) => new { t1, t2 })
.SelectMany(t => t.t2.DefaultIfEmpty(), (t, t2) => new { t1 = @t.t1, t2 });
Be aware, if you want to join on multiple columns, you have to name the properties the same with the same data type. Read more: "LINQ Joins on multiple columns in Entity Framework".
The proposal
The proposal on GitHub by no less than @roji itself, would add the LeftJoin
operator as a first class citizen. The query above would look like this:
var query = _dbContext
.Table1
.LeftJoin(_dbContext.Table2, t1 => t1.T2Id, t2 => t2.Id, (t1, t2) => new { t1, t2 });
As of the time of writing (4th December 2024), it is unclear whether or not the query syntax will have a new keyword representing the LeftJoin
operator. But it is likely that it will be added to the method syntax. If not - head over to the linked article and give it a thumbs up.