Sunday, April 17, 2011

LINQ to SQL Left Outer Join

Hi,

Is this query equivalent to a LEFT OUTER join?

//assuming that I have a parameter named 'invoiceId' of type int
from c in SupportCases
let invoice = c.Invoices.FirstOrDefault(i=> i.Id == invoiceId)
where (invoiceId == 0 || invoice != null)    
select new 
{
      Id = c.Id
      , InvoiceId = invoice == null ? 0 : invoice.Id
}
From stackoverflow
  • 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.OrderID == 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

0 comments:

Post a Comment