【发布时间】:2015-11-14 06:41:48
【问题描述】:
所以我正在尝试构建一个半复杂的搜索表达式,但我一直在尝试创建一个基本的表达式。用于 getValueExpression 的表达式类似于:
x => x.PropertyA != null ? x.PropertyA.ToShortDateString() : "" //nullable datetime
x => x.PropertyB //string property
x => x.PropertyC != null x.PropertyC.ToString() : "" //nullable int
这是我的函数代码,当 getValueExpression 的类型为 Func 时出现错误,无法与字符串进行比较,这很有意义,我理解为什么会这样,但我无法弄清楚如何制作一个表达式,它获取 getValueExpression 的值以与正在搜索的值进行比较。任何帮助或正确方向的线索将不胜感激。
public static IQueryable<TSource> Search<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, string>> getValueExpression, string searchOption, string searchValue)
{
var searchValueExpression = Expression.Constant(searchValue);
var comparisonExpression = Expression.Equal(getValueExpression, searchValueExpression);
var lambdaExpression = Expression.Lambda<Func<TSource, bool>>(comparisonExpression);
return source.Where(lambdaExpression);
}
我已经尝试过类似的事情,但是遇到了错误的参数数量异常的失败:
var getValueExpressionValue = Expression.Call(getValueExpression.Compile().Method, parameterValueExpression);
【问题讨论】:
标签: c# .net expression entity-framework-6 iqueryable