IQueryable<> dynamic ordering/filtering with GetValue fails

前端 未结 1 1952
名媛妹妹
名媛妹妹 2021-01-20 04:26

I\'m attempting to filter results from a database using Entity Framework CTP5. Here is my current method.

IQueryable
Forms = DataContext.CreateFo
相关标签:
1条回答
  • 2021-01-20 04:52
    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.

    0 讨论(0)
提交回复
热议问题