views:

5413

answers:

2

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
}
+15  A: 

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)

Marc Gravell
+1  A: 
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

Krishnaraj Barvathaya