Trying to write a way to sort of dynamically look at data passed to me via json (I don't have it strictly typed). I have been mulling this over for days and I am 100% unsure of the syntax, but I get the concept.
Can anyone assist me write this so it works? The first 'if' needs to create a Linq "contains" with StringComparer.OrdinalIgnoreCase and the second if needs to create a Guid.Equals call.
I feel like a true idiot, but it has been close to 2 days and endless google searches. I even read the interface for the .Call commands and theres ~14 of them and I can't figure out which is for what. I haven't been able to get this to work even once.
public static IQueryable<T> FilterDynamic<T>(this IQueryable<T> query, string fieldName, object values)
{
ParameterExpression param = Expression.Parameter(typeof(T), "e");
MemberExpression prop = Expression.PropertyOrField(param, fieldName);
// We use nullable guids in <T>, so i have to convert to actual guid
UnaryExpression convertedExp = Expression.Convert(prop, prop.Type.GenericTypeArguments.Single());
MethodCallExpression body;
if (convertedExp.Type == typeof(string))
{
body = Expression.Call(typeof(Enumerable), "Contains", new[] {typeof(string)},
Expression.Constant(values), prop);
}
if (convertedExp.Type == typeof(Guid))
{
MethodInfo methd = convertedExp.Type.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public, null,new Type[] { typeof(object) }, null);
body = Expression.Call(prop.Type, "Equals", new[] {typeof(string)}, Expression.Constant(values), prop);
}
// Other types need to just not do anything.
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(body, param);
return query.Where(predicate);
}
The error I get on line 35 is No generic method 'Equals' on type 'System.Guid' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.
EDIT:
I had to change my second if block like this:
body = Expression.Call(convertedExp, methd, Expression.Constant(values));
All my answers were found by reading this code https://github.com/dotnet/corefx/blob/master/src/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs