LINQ to SQL左外部连接
这个查询是否等价于一个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。 要做一个左外连接,你需要SelectMany
和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.OrderID == null ? -1 : x.OrderID};
( 或通过扩展方法 )
你不需要进入语句:
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
是的,上面的查询确实创build了一个LEFT OUTER连接。
链接到处理多个左连接的类似问题: Linq to Sql:多个左外连接
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
我find了1个解决scheme 如果要将这种SQL(左连接)转换成Linq实体…
SQL:
SELECT * FROM [JOBBOOKING] AS [t0] LEFT OUTER JOIN [REFTABLE] AS [t1] ON ([t0].[trxtype] = [t1].[code]) AND ([t1]. [reftype] = "TRX")
LINQ:
from job in JOBBOOKINGs join r in (from r1 in REFTABLEs where r1.Reftype=="TRX" select r1) on job.Trxtype equals r.Code into join1 from j in join1.DefaultIfEmpty() select new { //cols... }
我想补充一点。 在LINQ to SQL中,如果您的数据库已经正确构build并且您的表通过外键约束相关联,那么您根本不需要进行连接。
使用LINQPad我创build了下面的LINQ查询:
//Querying from both the CustomerInfo table and OrderInfo table from cust in CustomerInfo where cust.CustomerID == 123456 select new {cust, cust.OrderInfo}
哪个被转换为下面的(稍微截断的)查询
-- Region Parameters DECLARE @p0 Int = 123456 -- EndRegion SELECT [t0].[CustomerID], [t0].[AlternateCustomerID], [t1].[OrderID], [t1].[OnlineOrderID], ( SELECT COUNT(*) FROM [OrderInfo] AS [t2] WHERE [t2].[CustomerID] = [t0].[CustomerID] ) AS [value] FROM [CustomerInfo] AS [t0] LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID] WHERE [t0].[CustomerID] = @p0 ORDER BY [t0].[CustomerID], [t1].[OrderID]
注意上面的LEFT OUTER JOIN
。