Monday, July 27, 2015

Left Outer Join using LINQ

Left outer joins are another example of something that's seems intuitive in SQL but appears foreign in LINQ.  Here we have two tables, TableOne and TableTwo both with a common TableOneId column.  TableOne always has a record and TableTwo has 0 to many records for each TableOne record.  The first query will return every record from both tables even if the TableOne record has no TableTwo record.  The second query will only return records from TableOne only if they have no corresponding TableTwo record.  By the way, this is VB.


'Without a where clause

Dim Query = 
    From t1 In TableOnes
    Group Join t2 In TableTwos On t1.TableOneId Equals t2.TableOneId Into gj = Group
    From grouping In gj.DefaultIfEmpty
    Select t1, grouping


'With a where clause

Dim Query = 
    From t1 In TableOnes
    Group Join t2 In TableTwos On t1.RecordId Equals t2.RecordId Into gj = Group
    From grouping In gj.DefaultIfEmpty
    Where grouping Is Nothing
    Select t1, grouping
 

No comments:

Post a Comment