通过动态参数订购 [英] Order by dynamic parameter

查看:28
本文介绍了通过动态参数订购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用动态参数进行订购,这是代码:

I'm trying to make and order by with dynamic parameter, this is the code:

var res = from c in db.CUSTOMERS select c;

if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
      {
       var property = typeof(CUSTOMERS).GetProperty(sortBy);

       if(direction == "asc")
         {
            res = res.OrderBy(x => property.GetValue(x));
         }
      else
         {
           res = res.OrderBy(x => property.GetValue(x));
         } 
}

return res.ToList();

但是我得到这个错误:

LINQ to Entities无法识别方法'System.Object GetValue(System.Object)',并且该方法无法转换为商店表达式.

LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression.

推荐答案

如果要在服务器端进行排序,则必须更正表达式.

If you want to do sorting on the Server Side, you have to correct expression.

 var query = from c in db.CUSTOMERS select c;
    
 if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
 {
    query = query.ApplyOrderBy(new [] {Tuple.Create(sortBy, direction != "asc")});
 }

 return query.ToList();

实施:

public static class QueryableExtensions
{
    public static IQueryable<T> ApplyOrderBy<T>(this IQueryable<T> query, IEnumerable<Tuple<string, bool>> order)
    {
        var expr = ApplyOrderBy(typeof(T), query.Expression, order);
        return query.Provider.CreateQuery<T>(expr);
    }

    static Expression MakePropPath(Expression objExpression, string path)
    {
        return path.Split('.').Aggregate(objExpression, Expression.PropertyOrField);
    }

    static Expression ApplyOrderBy(Type entityType, Expression queryExpr, IEnumerable<Tuple<string, bool>> order)
    {
        var param = Expression.Parameter(entityType, "e");
        var isFirst = true;
        foreach (var tuple in order)
        {
            var lambda = Expression.Lambda(MakePropPath(param, tuple.Item1), param);
            var methodName =
                isFirst ? tuple.Item2 ? nameof(Queryable.OrderByDescending) : nameof(Queryable.OrderBy)
                : tuple.Item2 ? nameof(Queryable.ThenByDescending) : nameof(Queryable.ThenBy);

            queryExpr = Expression.Call(typeof(Queryable), methodName, new[] { entityType, lambda.Body.Type }, queryExpr, lambda);
            isFirst = false;
        }

        return queryExpr;
    }
}

这篇关于通过动态参数订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆