简体   繁体   中英

Linq To Entity string to int conversion in order by

There is a table in our database the stores year and month, each being a char. The existing Linq to Entity query looks like this:

from mc in repository.table.AsQueryable()
orderby mc.Year descending, mc.Month descending
select mc).FirstOrDefault()

The issue with this is that it is ordering by string and not int, leading to the incorrect row being returned from the query. I have tried to convert the year and month to int and datetime, both throwing an error saying:

"LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression."

(from mc in repository.table.AsQueryable()
 orderby mc.Year descending, Convert.ToDateTime(mc.Month) descending
 select mc).FirstOrDefault()

OR

"LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression."

(from mc in repository.table.AsQueryable()
 orderby mc.Year descending, Convert.ToInt32(mc.Month) descending
 select mc).FirstOrDefault();

As you can see, I cannot cast the month and year into INTs first because it is using the data from the table, not external data.

PS: I do not have the authority to change the tables to make the two columns INTs.

Anyone know how to approach this?

我建议您看一下SqlFunctions类,最值得注意的是有关DatePart方法的信息,该方法可与Entity Framework一起使用(无例外),并将字符串转换为日期以供您正确排序。

As @IronMan84 noticed solution below works only if you have .edmx file.

  1. Add the following xml to your .edmx file. (Just do a 'Find in Files' in Visual Studio </Schema> and place it before this node):

    <Function Name="IntParse" ReturnType="Edm.Int32"> <Parameter Name="stringvalue" Type="Edm.String" /> <DefiningExpression> cast(stringvalue as Edm.Int32) </DefiningExpression> </Function>

  2. Add the following static function to your auto-generated Entity Framework class file:

    public partial class YourObjectContext { [EdmFunction("YourModel", "IntParse")] public static double IntParse(string val) { return int.Parse(val); } }

  3. You are ready to go, just add the new function to your LINQ Query:

    from mc in repository.table.AsQueryable() orderby YourObjectContext.IntParse(mc.Year) descending, YourObjectContext.IntParse(mc.Month) descending select mc).FirstOrDefault()

您是否尝试过:

(from mc in repository.table.AsQueryable() orderby ((int)mc.Year) descending, ((int)mc.Month) descending select mc).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM