开发者

Convert an expression tree for a c# query expression

I am having a problem converting this query via an expression tree:

WageConstIn => Convert.ToString(WageConstIn.Serialno).StartsWith("2800")

This is my expression tree:

var searchTextExp = LinqExpression.Constant("2800");
var parameterExp  = LinqExpression.Parameter(typeof(WageConstInEntity), "WageConstIn");
var propertyExp   = LinqExpression.Property(parameterExp, "Serialno");
var convertExpr   = LinqExpression.Parameter(typeof(Convert), "Convert");                   
var toStringExp   = LinqExpression.Call(convertExpr, "ToString", new[] { typeof(decimal) }, new[] { propertyExp });
var startsWithExp = LinqExpression.Call(toStringExp, "StartsWith", null, new[] { searchTextExp });

I am getting the following error:

"No method 'ToString' on type 'System.Convert开发者_Python百科' is compatible with the supplied arguments"


The Convert.ToString Method (Decimal) is static (the Convert Class is a static class) and doesn't have any generic type parameters.

Use the Expression.Call Method (Type, String, Type[], Expression[]):

Creates a MethodCallExpression that represents a call to a static (Shared in Visual Basic) method by calling the appropriate factory method.

Example:

var toString = Expression.Call(typeof(Convert), "ToString", null, propertyExp);

(Also note that Convert.ToString is not generic, so you should provide null for the typeArguments parameter.)


It is an LLBLGEN problem and I have solved it using FunctionMapping as follows:

public class FunctionMappings : FunctionMappingStore
   {
    public FunctionMappings()
        : base()
    {
        FunctionMapping mapping = new FunctionMapping(typeof(Functions), "Like", 2, "{0} LIKE {1}");
        this.Add(mapping);
    }
}

public class Functions
{
    public static bool Like(string field, string value)
    {
        return true;
    }

    public static bool Like(decimal field, string value)
    {
        return true;
    }
}

I then proceeded to call the create the linq expression as follows:

ConstantExpression searchTextExp = Expression.Constant(string.Format("{0}%", searchText));
ParameterExpression parameterExp =    Expression.Parameter(typeof(ViewWageConstInEntity), "WageConstIn");
MemberExpression propertyExp = Expression.Property(parameterExp, searchField);
MethodCallExpression likeExpr = null;

if (propertyExp.Type == typeof(decimal))
{
    likeExpr = LinqExpression.Call(
        typeof(Functions).GetMethod("Like", new[] { typeof(decimal), typeof(string) }),
                    propertyExp, searchTextExp);
}
else if (propertyExp.Type == typeof(string))
{
    likeExpr = Expression.Call(
        typeof(Functions).GetMethod("Like", new[] { typeof(string), typeof(string) }),
                    propertyExp, searchTextExp);
}

This generated the appropriate SQL in the db as follows:

WHERE ([Serialno] LIKE 'SearchText%')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜