像Expression Tree中的运算符一样

时间:2010-10-13 11:28:41

标签: .net linq entity-framework lambda expression-trees

我有一个Linq扩展方法,可以使用字符串值动态过滤Linq查询。例如:query.WhereHelper("columName", ">", 1)。我可以使用许多不同的过滤器运算符,如GreaterThan或NotEqual等,但不能使用“Like”。没有Expression.Like或Expression.StartsWith等。如何在Expression树中实现Like运算符?这是我的代码:

public static IQueryable<T> WhereHelper<T>(this IQueryable<T> source, string columnName, object value, string filterType)
{
    ParameterExpression table = Expression.Parameter(typeof(T), "");
    Expression column = Expression.PropertyOrField(table, columnName);
    Expression valueExpression = Expression.Convert(Expression.Constant(value), column.Type);
    Expression where = null;

    switch (filterType)
    {
        case "<":
            where = Expression.LessThan(column, valueExpression);
            break;
        case "<=":
            where = Expression.LessThanOrEqual(column, valueExpression);
            break;
        case "=":
            where = Expression.Equal(column, valueExpression);
            break;
        case ">":
            where = Expression.GreaterThan(column, valueExpression;
            break;
        case ">=":
            where = Expression.GreaterThanOrEqual(column, valueExpression);
            break;
        case "<>":
            where = Expression.NotEqual(column, valueExpression);
            break;
    }

    Expression lambda = Expression.Lambda(where, new ParameterExpression[] { table });

    Type[] exprArgTypes = { source.ElementType };

    MethodCallExpression methodCall = Expression.Call(typeof(Queryable),
                                                      "Where",
                                                      exprArgTypes,
                                                      source.Expression,
                                                      lambda);

    return (IQueryable<T>)source.Provider.CreateQuery<T>(methodCall);

2 个答案:

答案 0 :(得分:7)

您可以将Expression.Callstring.StartsWithstring.Containsstring.EndsWith等方法结合使用。消费代码将其转换回TSQL。请注意,对于LINQ-to-SQL,此处还有一些其他辅助函数,但不包含EF。

答案 1 :(得分:6)

您可以按如下方式定义LIKE表达式,

var propertyName = "Firstname";
var propertyValue= "xxxx";

MethodInfo refmethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var parameter = Expression.Parameter(typeof(T), "type");
var property = Expression.Property(parameter, propertyName);
var value = Expression.Constant(propertyValue, typeof(string));
var containsMethodExp = Expression.Call(property, refmethod, value);