Dynamic Linq 2 Sql using Expressions Trees raising exception “Binary Operator LessThan not defined for System.String and System.String”

ε祈祈猫儿з 提交于 2019-12-10 19:42:53

问题


I'm trying to write a dynamic Linq 2 Sql query using Expressions trees but I'm getting a exception telling me that the LessThan and GreaterThan operators are not defined for System.String and System.String, which i find odd, is that true? or am I doing something wrong?

Expression<Func<SomeDataContextType, string>> codeSelectorExpresion = 
    x => x.CodeColumn;
var row = Expression.Parameter(typeof(SomeDataContextType), "row");
var expression = 
   Expression.GreaterThan(
       Expression.Invoke(codeSelectorExpression, row),
       Expression.Constant("someString", typeof(string)));
//I'm trying to build something like SomeDataContextType.CodeColumn > "someString"

回答1:


Sorry, after strugling for a while i realized that the > and < operators on strings are implemented calling to string.CompareTo, so i updated the code to use the string.CompareTo method instead and it worked. Thank you anyway, Tthe expression need to be:

var expression =
    Expression.GreaterThan(
       Expression.Call(
            Expression.Invoke(codeSelectorExpression, row), 
            typeof(string).GetMethod("CompareTo", new[] {typeof(string)}),
            Expression.Constant("someString")),
       Expression.Constant(0, typeof(int)));


来源:https://stackoverflow.com/questions/2061398/dynamic-linq-2-sql-using-expressions-trees-raising-exception-binary-operator-le

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!