本文介绍了LINQ to SQL 左外连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此查询是否等同于 LEFT OUTER
连接?
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
}
推荐答案
不完全 - 因为每个左"左外连接中的行将匹配 0-n 右";行(在第二个表中),而您的行仅匹配 0-1.要进行左外连接,您需要SelectMany
和DefaultIfEmpty
,例如:
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 };
(或通过扩展方法)
这篇关于LINQ to SQL 左外连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!