Like operator in Expression Tree
I have a Linq extension method to dynamically filter Linq queries using string values. For example: query.WhereHelper("columName", ">", 1)
. I could use many different filter operators like GreaterThan or NotEqual etc. but not "Like". There is no Expression.Like or Expression.StartsWith etc. How can I implement Like operator to my Expression tree? Here's my code:
public static IQueryable<T> WhereHelper<T>(this IQueryable<T> source, string columnName, object value, string filterType)
{
ParameterExpression table = Expression.Parameter(typeof(T), "");
Expression column = Expressi开发者_如何学Goon.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);
You would use Expression.Call
with the string.StartsWith
, string.Contains
, string.EndsWith
etc methods. It is for the consuming code to translate it back to TSQL. Note that for LINQ-to-SQL there are also some additional helper functions here, but not with EF.
You can define LIKE expression as follows,
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);
精彩评论