I would like to create a LINQ join statement equivalent of a Left Join
My tables are set up like so:
Recipe
RecipeID
...
Instruction
RecipeID
StepID
SomeFlag
...
Equivalent SQL:
SELECT *
FROM Recipe r
LEFT JOIN Instruction i
ON r.RecipeID = i.RecipeID
AND SomeFlag > 0
This is what I have so far:
var tmp = db.Recipe
.GroupJoin(
db.Instruction,
r => r.RecipeID,
i => i.RecipeID,
(r, i) => new {r, i},
???);
Firstly, is GroupJoin the correct choice for this type of operation? From what I understand, Join is equivalent to the SQL ‘Inner Join’ and GroupJoin is equivalent to ‘Left Join’. Second, what is the correct syntax to obtain my desired result? I have been searching for a while and I can’t seem to find a suitable answer using extension methods.
Don’t forget to read the help from (
GroupJoin: MSDN http://msdn.microsoft.com/en-us/library/bb535047.aspx andJoinMSDN http://msdn.microsoft.com/fr-fr/library/bb534675.aspx)The last argument of the
GroupJoinandJoinis optional (by overload) and is not usually used.It is a function that allow you to specify how to compare
r.RecipeIDwithi.RecipeID. AsRecipeIDmust be an integer, using the default comparer is a good choice. So let it with:Now what you want to have is to remove all the instructions that have
SomeFlag > 0. Why not do this before joining?Like this:
Update
@usr has perfectly commented saying
Joinperforms an INNER JOIN.As you may have remarked, LINQ does not have different methods for INNER, OUTER, LEFT, RIGHT joins. To know the equivalent LINQ of a particular SQL join you may find help on MSDN ( http://msdn.microsoft.com/en-us/library/vstudio/bb397676.aspx ).
using extension methods it is a bit of an ugly solution: