我创建了一个名为CarInfo的实体,但我不确定如何用它的等效Linq格式编写这个SQL。
SELECT @PartKey = PartKey
FROM CarInfo
WHERE CarKey = @CarKey
AND RegKey = @RegKey
AND TransactionDate =
(SELECT MAX(TransactionDate)
FROM CarInfo
WHERE CarKey = @CarKey
AND RegKey = @RegKey
AND TransactionDate <= @TransactionDate)
答案 0 :(得分:0)
var query = from c in database.Cars
where c.CarKey == carKey &&
c.RegKey == regKey &&
c.TransactionDate == database.Cars.Where(c => c.CarKey == carKey && c.RegKey == regKey && c.TransactionDate < transactionDate).Max()
select c.PartKey;
foreach (var key in query)
{
//Do your work
}
//or
var onlyKey = query.FirstOrDefault();
其中:
答案 1 :(得分:0)
有一些真正的Linq专家潜伏在这些部分,但这是一个应该真正帮助你前进的初步尝试:
var results =
from carInfo in Context.CarInfos
where carInfo.CarKey == carKey && carInfo.RegKey == regKey &&
(carInfo.TransactionDate == (Context.CarInfos.Max(
(item) => item.CarKey == carKey && item.RegKey == regKey && item.TransactionDate < transactionDate)))
select carInfo.PartKey
答案 2 :(得分:0)
from carInfo in context.CarInfo
where carInfo.Key == carKey && carInfo.RegKey == regKey
&& carInfo.TransactionDate == (from c in carInfo
where c.CarKey == carKey && c.RegKey == regKey &&
c.TransactionDate <= transactionDate
select c.TransactionDate).Max()
select carInfo.PartKey
答案 3 :(得分:0)
我知道我可能不应该改变原始SQL语句的逻辑,但看起来它的目的是提供从最近的记录到最近的记录到某个特定日期的partkey。如果事实确实如此,我会考虑这个:
var result =(from ci in ctxt.CarInfos
where ci.CarKey == carKey
&& ci.RegKey == regKey
&& ci.TransactionDate <= transactionDate
orderby ci.TransactionDate descending
select ci.PartKey)
.FirstOrDefault();
结果将是partKey(如果没有找到记录则为null)。如果您想要与该日期匹配的所有记录,则必须在orderby之前对它们进行分组。