简体   繁体   中英

Greater than comparison for strings in EF

First off, I don't have any controll over the database so I can't change anything there.

The field in the database is a varchar(50) and contains (for the records I'm interested in) a number. I'd like to get all of them with a number over 50. In SQL I just type:

SELECT Field FROM MyTable WHERE Field > '50'

That works fine even though I can agree the datatype should be something else.

In EF I'm trying:

query = query.Where(t => t.MyTable.Field > string);

There error is: Operator '>' cannot be applied to operands of type 'string' and 'string'

use int.Parse(str) C# is not implicitly typed - ergo you have to convert it to an integer, double etc befoe using the '>' operator. If you are not sure if the string will be a number then you can use int.tryparse(str)

Originally, I suggested the below code, which I tried and worked but not using EF entity set:

query = query.Where(t => int.TryParse(t.Mytable.Field, out number) && int.Parse(t.MyTable.Field) > int.Parse(string));

And then, after getting some good comments, I tried it on EF set, and that line itself worked, but after that line executes, I tried to so anything on the results of the query above (eg Count()), I got the below exception:

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

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