这个SQL可以在LINQ中完成吗?
我有一个简单的 SQL 查询,但我很难在 LINQ 中复制,
select top 1 * from tbl_CarTax tax
ORDER BY ABS(tax.C02_From - 286.0)
我在下面尝试过,但收到错误... - LINQ to Entities 无法识别方法“Int32 ToInt32(System.Object)”方法,并且此方法无法转换为存储表达式。
TaxCost = (from tax in db.DB2011_Vehicle_CarTax
orderby Math.Abs(Convert.ToInt32(C02Level - tax.C02_From))
select tax).SingleOrDefault();
任何帮助都是最感激的
Truegilly
i have a simple SQL query, but im struggling to replicate in LINQ
select top 1 * from tbl_CarTax tax
ORDER BY ABS(tax.C02_From - 286.0)
i have tried this below but i get the error... - LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression.
TaxCost = (from tax in db.DB2011_Vehicle_CarTax
orderby Math.Abs(Convert.ToInt32(C02Level - tax.C02_From))
select tax).SingleOrDefault();
Any help is most appriciated
Truegilly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不需要
Convert.ToInt
。此外,FirstOrDefault
相当于top 1
。如果您的查询结果返回多行,SingleOrDefault
将引发异常。尝试使用此代码:
与其他答案相反,我认为没有必要避免使用 Math.Abs,因为实体框架知道此方法并可以将其转换为 SQL。
There is no need for
Convert.ToInt
. Additionally,FirstOrDefault
is the equivalent totop 1
.SingleOrDefault
will throw an exception, if your query results in more than one row being returned.Try using this code:
In contrast to the other answer, I see no need to avoid using
Math.Abs
, because the Entity Framework knows this method and can convert it to SQL.您可以提取所有数据,然后在记录集上使用 Math.Abs(如果需要提取大量信息,则可能会很慢),或者您可以执行如下操作:
可能有更合法的方法来执行此操作,但如果速度足够快,它应该可以工作。
编辑 - 实际上,Math.Abs 似乎可以很好地转换为 SQL。如果删除 Convert.Int32 它应该可以正常工作。
You can pull down all the data, then use Math.Abs on the record set (probably slow if there's a lot of info to pull down), or you can just do something like this:
There might be a more legitimate way to do this, but if this is fast enough it should work.
Edit - Actually, it appears that Math.Abs translates just fine to SQL. If you remove the Convert.Int32 it should work just fine.