How to write a dynamic linq method for Like
clause.
For.: the reference for Dynamic linq orderby is http://stackoverflow.com/questions/41244/dynamic-linq-orderby.
I am looking for a similar one for dynamic Like
clause.
I have the following extension methods for like:
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, string keyword)
{
var type = typeof(T);
var property = type.GetProperty(propertyName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constant = Expression.Constant("%" + keyword + "%");
MethodCallExpression methodExp = Expression.Call(null, typeof(SqlMethods).GetMethod("Like", new Type[] { typeof(string), typeof(string) }), propertyAccess, constant);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
The above method gives an error
Method 'Boolean Like(System.String, System.String)' cannot be used on the client; it is only for translation to SQL.
The other method which is somehow modified from http://stackoverflow.com/questions/41244/dynamic-linq-orderby:
public static IQueryable<T> ALike<T>(this IQueryable<T> source, string property, string keyword)
{
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
var constant = Expression.Constant("%" + keyword + "%");
MethodCallExpression methodExp = Expression.Call(null, typeof(SqlMethods).GetMethod("Like", new Type[] { typeof(string), typeof(string) }), expr, constant);
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, methodExp, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IQueryable<T>)result;
}
The above method gives an error:
Expression of type 'System.Boolean' cannot be used for return type 'System.String'
Any ideas on this?