I\'m attempting to filter results from a database using Entity Framework CTP5. Here is my current method.
IQueryable
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, string keyword) {
Type type = typeof(T);
ParameterExpression parameter = Expression.Parameter(type, "param");
MemberExpression memberAccess = Expression.MakeMemberAccess(parameter, type.GetProperty(propertyName));
ConstantExpression constant = Expression.Constant("%" + keyword + "%");
MethodInfo contains = memberAccess.Type.GetMethod("Contains");
MethodCallExpression methodExp = Expression.Call(memberAccess, contains, Expression.Constant(keyword));
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
You would call it like so
Forms = Forms.Like(header, filter);
I haven't done any validation of the passed parameters. For instance you have to validate that the Contains method exists on the type of the property you're validating against. So it won't work on an int
or anything like that.