扩展相关的子查询以在LINQ中包含另一个查询

时间:2018-05-06 08:36:49

标签: c# .net linq

我正在尝试扩展相关子查询以在LINQ中包含另一个查询。 在SQL中,这将是查询。

SELECT V.Car_ID
FROM VEHICLES V, AGREEMENTS A, AGREEMENTS A1
WHERE A.Car_ID = V.Car_ID
AND enDate >= A.Hire_Start_Date
AND stDate <= A.Hire_End_Date
AND A1.CAR_ID = V.CAR_ID
AND location = A1.Return_Location
AND A1.Return_date =
 (SELECT MAX(A2.Return_Date)
 FROM AGREEMENT A2
 WHERE A2.VEHICLE_ID = V.VEHICLE_ID
 AND A2.Return_Date < stDate)**

在一些帮助下,我已经查询车辆是否有协议,但我似乎无法扩展它以检查协议返回位置是否与搜索位置匹配。到目前为止,这是我的代码。

var cars = from v in db.VEHICLEs
                   where !db.AGREEMENTs.Any(a => (a.CAR_ID == v.CAR_ID
                   && a.STATUS_OPEN == true
                   && enDate >= a.HIRE_START_DATE
                   && strtDate <= a.HIRE_END_DATE))
                   select v;

我工作的LINQ查询中缺少以下部分的sql查询。

AND A1.CAR_ID = V.CAR_ID
AND location = A1.Return_Location
AND A1.Return_date =
 (SELECT MAX(A2.Return_Date)
 FROM AGREEMENT A2
 WHERE A2.VEHICLE_ID = V.VEHICLE_ID
 AND A2.Return_Date < stDate)**

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您的Sql查询是内部联接,因此在Linq中您可以执行:

var cars =  from v in db.VEHICLEs
            from a in db.AGREEMENTs
            from a1 in db.AGREEMENTs
            where a.CAR_ID == v.CAR_ID
                && enDate >= a.HIRE_START_DATE
                && strtDate <= a.HIRE_END_DATE
                && a1.CAR_ID == v.CAR_ID
                && location == a1.RETURN_LOCATION
                && a1.RETURN_DATE == db.AGREEMENTs
                    .Where(a2 => a2.VEHICLE_ID == v.VEHICLE_ID)
                    .Max(a2 => a2.RETURN_DATE)
            select v.CAR_ID;

要选择其他字段,您可以执行select new { CarId = v.CAR_ID, ... }

答案 1 :(得分:0)

非常感谢derloopkat,你让我在那里! :-)

             var cars = from v in db.VEHICLEs                       
                   from a1 in db.AGREEMENTs
                   where !db.AGREEMENTs.Any(a => (a.CAR_ID == v.CAR_ID
                       && a.STATUS_OPEN == true
                       && enDate >= a.HIRE_START_DATE
                       && strtDate <= a.HIRE_END_DATE))
                       && a1.CAR_ID == v.CAR_ID
                       && schPickUpDepotID == a1.RETURN_LOCATION
                       && a1.HIRE_END_DATE == db.AGREEMENTs
                        .Where(a2 => a2.CAR_ID == v.CAR_ID)
                        .Max(a2 => a2.HIRE_END_DATE)
                   select v;