Left joins are such a common occurrence in data access programs. There is no direct LINQ operator or syntax mapped for left joins. However, there is an extension method
DefaultIfEmpty() which can be employed to perform a left outer join using LINQ syntax.
DefaultIfEmptybasically returns a single element sequence with associated type’s default value in case source sequence is empty.
For ex: in code snippet below,
null if no match found in related
employee_associations object for given
employee_associations is a reference type
Following query attempts to retrieve optional
employee_discounts which are perfect candidates for left join because employee may or may not have discounts and associations.
Left outer join always return each element in first collection (
employees), regardless of whether it has any matching elements in the second collection (
employee_associations) or (
var query = (from e in context.employees
from ea in
context.employee_associations.Where(a => a.employeeId == e.employeeId)
from ed in
context.employee_discounts.Where(d => d.employeeId == e.employeeId)
EmpName = e.employeeName,
DiscountName = ed!= null ? ed.discountName: null,
AssociationName = ea!= null ? ea.associationName: null