OrderBy extension method for NPoco.Linq

2019-07-16 00:25发布

问题:

I want to use OrderBy("columnName").

I see that it is possible by writing an extension method or using reflection.

I am using NPoco and I am unable to write an extension method.

IQueryProvider<Sample> query =  DbConnection.Query<Sample>();

I want to do:

var res = query.OrderByField("columnName");

I want to use something similar to this:

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
    var param = Expression.Parameter(typeof(T), "p");
    var prop = Expression.Property(param, SortField);
    var exp = Expression.Lambda(prop, param);
    string method = Ascending ? "OrderBy" : "OrderByDescending";
    Type[] types = new Type[] { q.ElementType, exp.Body.Type };
    var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
}

The above wont work since I am passing IQueryProvider instead of IQueryable.

回答1:

Try the following code

public static IQueryProvider<T> OrderByField<T>(this IQueryProvider<T> q, string SortField, bool Ascending)
{
    var param = Expression.Parameter(typeof(T), "p");
    var prop = Expression.Property(param, SortField);
    string methodName = Ascending ? "OrderBy" : "OrderByDescending";
    Expression conversion = Expression.Convert(prop, typeof(object));
    LambdaExpression lambda = Expression.Lambda(conversion, param);
    object result = typeof(IQueryProvider<T>).GetMethods().Single(
            method => method.Name == methodName)
        .Invoke(q, new object[] { lambda });
    return (IQueryProvider<T>)result;
}

Then apply the query.

var list = db.Query<Users>().OrderByField("Id",false).ToList();


标签: c# linq npoco