我对Linq很新手,但我必须将几个复杂的SQL查询转换为Linq,所以我买了一份Linqer。不幸的是我知道有一个SQL查询Linqer无法转换为Linq,因为Linqer无法转换带子连接的SQL。我希望有人可以帮我解决这个SQL查询的Linq代码:
SELECT v.*, rci.CustomId, ci.EntryTime As CheckInTime, ci.Operator As CheckInOperator,
cis.Name As CheckInStation, co.EntryTime As CheckOutTime, co.Operator As CheckOutOperator,
cos.Name As CheckOutStation, cat.Name As Category, clr.Name As Clearance, r.ReasonForVisit As Reason,
s.SiteId + ' -- ' + s.SiteName As Site, e.LastName + ', ' + e.FirstName As Employee
FROM ((((((((((Visitor v LEFT JOIN VisitorEntry ci ON v.CheckInId = ci.Id)
LEFT JOIN VisitorEntry co ON v.CheckOutId = co.Id)
LEFT JOIN Station cis ON ci.StationId = cis.Id)
LEFT JOIN Station cos ON co.StationId = cos.Id)
LEFT JOIN Category cat ON v.CategoryId = cat.Id)
LEFT JOIN Clearance clr ON v.ClearanceId = clr.Id)
LEFT JOIN Reason r ON v.ReasonId = r.Id)
LEFT JOIN Site s ON v.SiteId = s.Id)
LEFT JOIN Employee e ON v.EmployeeId = e.Id)
LEFT JOIN RecordCustomId rci ON v.Id = rci.ParentId)
WHERE 1=1
(我有几个类似于我需要转换为Linq的SQL查询,这就是为什么我在查询中有“WHERE”占位符。)
此外,我一直在看这篇博文,但我仍然无法理解如何翻译我的查询: http://codingsense.wordpress.com/2009/06/16/multiple-list-left-join-in-linq/
谢谢! 麦克
答案 0 :(得分:2)
你的SQL中所有这些括号的重点是什么,它们似乎没有做任何事情,如果它们被删除,你得不到完全相同的结果吗?您使用DefaultIfEmpty方法在linq中执行左连接。我猜你正在使用LinqToSql?以下是我最近参与的一个项目的例子
return from app in pi_GetApplications()
from names in app.tContact.tNames // Inner Join
from addr in app.tContact.tAddresses.DefaultIfEmpty() // Left Outer Join
select app;
这假设您具有DBML文件中定义的外键的关联,以便LinqtoSql知道实体的关联方式。