LINQ to SQL Left Outer Join LINQ to SQL Left Outer Join database database

LINQ to SQL Left Outer Join


You don't need the into statements:

var query =     from customer in dc.Customers    from order in dc.Orders         .Where(o => customer.CustomerId == o.CustomerId)         .DefaultIfEmpty()    select new { Customer = customer, Order = order }     //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins:Linq to Sql: Multiple left outer joins


Not quite - since each "left" row in a left-outer-join will match 0-n "right" rows (in the second table), where-as yours matches only 0-1. To do a left outer join, you need SelectMany and DefaultIfEmpty, for example:

var query = from c in db.Customers            join o in db.Orders               on c.CustomerID equals o.CustomerID into sr            from x in sr.DefaultIfEmpty()            select new {               CustomerID = c.CustomerID, ContactName = c.ContactName,               OrderID = x == null ? -1 : x.OrderID };   

(or via the extension methods)


Public Sub LinqToSqlJoin07()Dim q = From e In db.Employees _        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _        From o In ords.DefaultIfEmpty _        Select New With {e.FirstName, e.LastName, .Order = o}ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx