OrderBy extension method for NPoco.Linq

夙愿已清 提交于 2019-12-12 17:16:03

问题


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();


来源:https://stackoverflow.com/questions/48448548/orderby-extension-method-for-npoco-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!