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
There is no need for
Convert.ToInt. Additionally,FirstOrDefaultis the equivalent totop 1.SingleOrDefaultwill 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.