具有LINQ to Entities的表达式树中的TrimStart

时间:2013-09-03 22:08:33

标签: c# entity-framework expression-trees

我正在尝试编写一个表达式树,它允许使用Entity Framework在非字符串值列上动态使用StartsWith()方法。

E.g。 IntegerValuedColumn.StartsWith(5)将返回50050005555123

我正在尝试根据这个答案写一个表达式树:

How do I query an integer column for "starts with" in Entity Framework?

这是我到目前为止所做的:

MethodInfo stringConvert = typeof(SqlFunctions).GetMethod("StringConvert", new[] { typeof(double?) });

Expression castExpression = Expression.Convert(propertyExpression, typeof(double?));

Expression convertExpression = Expression.Call(null, stringConvert, castExpression);

MethodInfo trimStart = typeof(string).GetMethod("TrimStart");

Expression nullExpression = Expression.Constant(null, typeof(char[]));
Expression trimExpression = Expression.Call(convertExpression, trimStart, nullExpression);

MethodInfo startsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });

Expression methodExpression = Expression.Call(trimExpression, startsWith, constantExpression);

return methodExpression;

当我编译并运行此表达式时,我得到以下异常:

当没有指定修剪字符作为参数时,只有LINQ to Entities支持'System.String TrimStart(Char [])'方法。

在原始示例中,表达式为:

SqlFunctions.StringConvert((double)x.AccountNumber)
    .TrimStart().StartsWith(searchTerm)

但我得到的是:

StringConvert(Convert(x.AccountNumber)).TrimStart(null).StartsWith(searchTerm)

我删除了处理TrimStart的两行(nullExpression和trimExpression)并验证该语句是否运行(不包括错误是由不同语言使用引起的)。我的基于异常消息的理论是TrimStart()方法想要使用零参数调用,但是当我尝试表达式构建器告诉我传递了不正确数量的参数时,我想我只是缺少东西。

我如何使用表达式树来调用TrimStart()而不是TrimStart(null)TrimStart(new char[0])之类的TrimStart方法?

0 个答案:

没有答案
相关问题