按动态参数排序

hou*_*ous 0 c# linq entity-framework

我正在尝试使用动态参数进行制作和排序,这是代码:

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

但我收到此错误:

LINQ to Entities 无法识别“System.Object GetValue(System.Object)”方法,并且该方法无法转换为存储表达式。

在此输入图像描述

Svy*_*liv 7

如果要在服务器端进行排序,则必须正确表达。

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

和实施:

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