IQueryable <> dynamic ordering / filtering with GetValue error

I am trying to filter results from a database using Entity Framework CTP5. Here is my current method.

IQueryable<Form> Forms = DataContext.CreateFormContext().Forms;
foreach(string header in Headers) {
    Forms = Forms.Where(f => f.GetType()
                              .GetProperty(header)
                              .GetValue(f, null)
                              .ToString()
                              .IndexOf(filter,
                                  StringComparison.InvariantCultureIgnoreCase) >= 0);
}

However, I found that GetValue does not work using the Entity Framework. This happens when the type is if IEnumerable<>, but notIQueryable<>

Is there an alternative that I can use to get the same effect?

+2
source share
1 answer
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);
}

Would you call it that

Forms = Forms.Like(header, filter);

. , , Contains , . int - .

+3

Source: https://habr.com/ru/post/1787832/


All Articles