C# 如何用Linq写这个?
我已经创建了一个名为CarInfo的实体,但我不确定如何以它的等效Linq形式编写此SQLC# 如何用Linq写这个?,c#,linq-to-entities,C#,Linq To Entities,我已经创建了一个名为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 RegK
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)
其中:
Cars是您的表,相应地替换为EF或Linq2SQL
regKey、carKey和transactionDate是带有您的值的局部变量
您需要使用EF或Linq2SQL正确设置汽车类
有一些真正的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
我知道我可能不应该更改原始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之前对其进行分组。子查询包含不必要的检查:和TransactionDate抱歉,它应该已读取和TransactionDate Hi Jon,在您的解决方案中,query=c.PartKey是否执行过?它将是c.PartKey的IEnumerable,您需要在其上运行foreach或调用query.FirstOrDefault,以适用于您的情况为准。如果c.PartKey是一个字符串,您将得到一个IEnumerable,如果查询没有结果,FirstOrDefault将返回一个字符串或null。嗨,Jon,我在where上得到一个错误,说Delegate…不接受1参数。有什么想法吗?嗨,骰子,我用你的方法犯了几个错误。where表示carinfo不接受1个参数,下一行表示运算符==不能应用于string或int类型的操作数。@Brian您的变量carKey、regKey和transactionDate必须与数据库中相应列的类型相同。如果ci.carKey是整数,则carKey也必须是整数。谢谢,我似乎总是错过显而易见的事情!
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
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();