Dot-Net

LINQ to SQL 左外連接

  • March 31, 2009

此查詢是否等同於LEFT OUTER聯接?

//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
}

不完全——因為左外連接中的每個“左”行都將匹配 0-n 個“右”行(在第二個表中),而你的只匹配 0-1。要進行左外連接,您需要SelectManyand DefaultIfEmpty,例如:

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 };   

或通過擴展方法

您不需要 into 語句:

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

是的,上面的查詢確實創建了一個 LEFT OUTER 連接。

連結到處理多個左連接的類似問題: Linq to Sql: Multiple left outer joins

引用自:https://stackoverflow.com/questions/700523