我正在尝试将sql查询转换为LINQ,但在写入查询后无法从结果集中获取记录
SELECT T.ServiceOrderNo,T.STATUS, T.SubStatus,T.orderVersion,T.OrderDate
,@pid, T.EventID, 'FOI'
FROM #temp1 T
LEFT JOIN Tbl_Service_Order_Progress O ON T.ServiceOrderNo DATABASE_DEFAULT = O.ServiceOrderNo
AND O.PARENTID = @pid
AND O.ServiceOrderType = 'FOI'
WHERE O.ServiceOrderNo IS NULL
以上我正在尝试使用LINQ
var lstInsertFOI = (from i in lstFOI
join j in lstSOP on i.fulfilmentOrderItemIdentifier equals j.ServiceOrderNo into res
from subRight in res.DefaultIfEmpty()
where subRight.ParentId == parentId && subRight.ServiceOrderNo == null && subRight.ServiceOrderType.Equals("FOI")
select new
{
ServiceOrderNo = subRight.ServiceOrderNo == null ? i.fulfilmentOrderItemIdentifier : subRight.ServiceOrderNo,
EventStatus = i.status,
EventSubStatus = i.subStatus,
OrderVersion = i.orderVersion,
EVENTRECEIVEDDATE = i.orderDate,
ParentId = parentId,
EventID = i.eventID,
ServiceOrderType = "FOI",
}).ToList();
以上linq查询不会获取预期结果,该结果应返回lstFOI列表中的记录数,但不返回任何记录。 linq查询是否正确?
答案 0 :(得分:0)
让我们从SQL查询开始。
LEFT JOIN Tbl_Service_Order_Progress O
ON T.ServiceOrderNo = O.ServiceOrderNo
AND O.PARENTID = @pid AND O.ServiceOrderType = 'FOI'
相当于
LEFT JOIN (SELECT * FROM Tbl_Service_Order_Progress
WHERE PARENTID = @pid AND ServiceOrderType = 'FOI') O
ON T.ServiceOrderNo = O.ServiceOrderNo
然后
WHERE O.ServiceOrderNo IS NULL
表示查询实际上是使用反连接,即包含左侧的所有记录,不具有来自右侧的匹配记录。< / p>
考虑到所有这些,等效的LINQ查询应该是这样的:
var lstInsertFOI = (
from i in lstFOI
join j in lstSOP
.Where(e => e.ParentId == parentId && subRight.ServiceOrderType == "FOI")
on i.fulfilmentOrderItemIdentifier equals j.ServiceOrderNo into res
where !res.Any()
select new
{
ServiceOrderNo = i.fulfilmentOrderItemIdentifier,
EventStatus = i.status,
EventSubStatus = i.subStatus,
OrderVersion = i.orderVersion,
EVENTRECEIVEDDATE = i.orderDate,
ParentId = parentId,
EventID = i.eventID,
ServiceOrderType = "FOI",
}).ToList();