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
}
I found 1 solution. if want to translate this kind of SQL (left join) into Linq Entity...
SQL:
LINQ:
I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.
Using LINQPad I created the following LINQ query:
Which was translated to the (slightly truncated) query below
Notice the
LEFT OUTER JOIN
above.You don't need the into statements:
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
Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx
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
andDefaultIfEmpty
, for example:(or via the extension methods)