使用GetValue的IQueryable <>动态排序/过滤失败

MyN*_*Job 3 c# entity-framework

我正在尝试使用Entity Framework CTP5从数据库中过滤结果。这是我目前的方法。

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);
}
Run Code Online (Sandbox Code Playgroud)

但是,我发现GetValue在使用实体框架时不起作用。如果IEnumerable<>不是,它会在类型时执行IQueryable<>

我可以使用其他方法产生相同的效果吗?

Bui*_*ted 5

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);
}
Run Code Online (Sandbox Code Playgroud)

你会这样称呼它

Forms = Forms.Like(header, filter);
Run Code Online (Sandbox Code Playgroud)

我尚未对传递的参数进行任何验证。例如,您必须验证所针对的属性类型上是否包含Contains方法。因此,它不适用于int或类似功能。