12

我正在寻找一种方法来存储Expression<Func<T, TProperty>>用于排序元素的集合,然后针对IQueryable<T>对象执行存储的列表(底层提供程序是实体框架)。

例如,我想做这样的事情(这是伪代码):

public class Program
{
    public static void Main(string[] args)
    {
        OrderClause<User> orderBys = new OrderClause<User>();
        orderBys.AddOrderBy(u => u.Firstname);
        orderBys.AddOrderBy(u => u.Lastname);
        orderBys.AddOrderBy(u => u.Age);

        Repository<User> userRepository = new Repository<User>();
        IEnumerable<User> result = userRepository.Query(orderBys.OrderByClauses);
    }
}

一个 order by 子句(订购的属性):

public class OrderClause<T>
{
    public void AddOrderBy<TProperty>(Expression<Func<T, TProperty>> orderBySelector)
    {
        _list.Add(orderBySelector);
    }

    public IEnumerable<Expression<Func<T, ???>>> OrderByClauses
    {
        get { return _list; }
    }
}

带有我的查询方法的存储库:

public class Repository<T>
{
    public IEnumerable<T> Query(IEnumerable<OrderClause<T>> clauses)
    {
        foreach (OrderClause<T, ???> clause in clauses)
        {
            _query = _query.OrderBy(clause);
        }

        return _query.ToList();
    }
}

我的第一个想法是将 转换Expression<Func<T, TProperty>>为字符串(要排序的属性名称)。所以基本上,我没有存储一个类型化的列表(这是不可能的,因为 TProperty 不是常量),我存储了一个字符串列表,其中包含要排序的属性。

但这不起作用,因为那时我无法重建Expression背面(我需要它,因为 IQueryable.OrderBy 需要一个Expression<Func<T, TKey>>作为参数)。

我还尝试动态创建表达式(在 Expression.Convert 的帮助下),Expression<Func<T, object>>但后来我从实体框架中得到一个异常,说它无法处理 Expression.Convert 语句。

如果可能的话,我不想使用像Dynamic Linq Library这样的外部库。

4

4 回答 4

11

dynamic这是/ 反射解决方案可能适用的少数情况之一。

我想你想要这样的东西?(我已经阅读了字里行间,并在我认为必要的地方对您的结构进行了一些更改)。

public class OrderClauseList<T>
{
    private readonly List<LambdaExpression> _list = new List<LambdaExpression>();

    public void AddOrderBy<TProperty>(Expression<Func<T, TProperty>> orderBySelector)
    {
        _list.Add(orderBySelector);
    }

    public IEnumerable<LambdaExpression> OrderByClauses
    {
        get { return _list; }
    }
}

public class Repository<T>
{
    private IQueryable<T> _source = ... // Don't know how this works

    public IEnumerable<T> Query(OrderClause<T> clauseList)
    {
        // Needs validation, e.g. null-reference or empty clause-list. 

        var clauses = clauseList.OrderByClauses;

        IOrderedQueryable<T> result = Queryable.OrderBy(_source, 
                                                        (dynamic)clauses.First());

        foreach (var clause in clauses.Skip(1))
        {
            result = Queryable.ThenBy(result, (dynamic)clause);
        }

        return result.ToList();
    }
}

关键技巧是让 C#dynamic为我们做可怕的重载解析和类型推断。更重要的是,我相信上面的内容,尽管使用了dynamic,实际上是类型安全的!

于 2013-05-22T13:52:55.210 回答
3

一种方法是将所有排序子句“存储”在类似的东西Func<IQueryable<T>, IOrderedQueryable<T>>(即调用排序方法的函数)中:

public class OrderClause<T>
{
    private Func<IQueryable<T>, IOrderedQueryable<T>> m_orderingFunction;

    public void AddOrderBy<TProperty>(Expression<Func<T, TProperty>> orderBySelector)
    {
        if (m_orderingFunction == null)
        {
            m_orderingFunction = q => q.OrderBy(orderBySelector);
        }
        else
        {
            // required so that m_orderingFunction doesn't reference itself
            var orderingFunction = m_orderingFunction;
            m_orderingFunction = q => orderingFunction(q).ThenBy(orderBySelector);
        }
    }

    public IQueryable<T> Order(IQueryable<T> source)
    {
        if (m_orderingFunction == null)
            return source;

        return m_orderingFunction(source);
    }
}

这样,您不必处理反射或dynamic,所有这些代码都是类型安全的并且相对容易理解。

于 2013-05-22T17:34:45.327 回答
2

您可以将 lambda 表达式作为该LambdaExpression类型的实例存储在集合中。

或者更好的是,存储排序定义,每个定义,除了一个表达式,还存储一个排序方向。

假设您有以下扩展方法

public static IQueryable<T> OrderBy<T>(
    this IQueryable<T> source,
    SortDefinition sortDefinition) where T : class
{
    MethodInfo method;
    Type sortKeyType = sortDefinition.Expression.ReturnType;
    if (sortDefinition.Direction == SortDirection.Ascending)
    {
        method = MethodHelper.OrderBy.MakeGenericMethod(
            typeof(T),
            sortKeyType);
    }
    else
    {
        method = MethodHelper.OrderByDescending.MakeGenericMethod(
            typeof(T),
            sortKeyType);
    }

    var result = (IQueryable<T>)method.Invoke(
        null,
        new object[] { source, sortDefinition.Expression });
    return result;
}

和类似的方法ThenBy。然后你可以做类似的事情

myQueryable = myQueryable.OrderBy(sortDefinitions.First());

myQueryable = sortDefinitions.Skip(1).Aggregate(
   myQueryable,
   (current, sortDefinition) => current.ThenBy(sortDefinition));

以下是和的SortDefinition定义MethodHelper

public class SortDefinition
{
    public SortDirection Direction
    {
        get;
        set;
    }

    public LambdaExpression Expression
    {
        get;
        set;
    }
}

internal static class MethodHelper
{
    static MethodHelper()
    {
        OrderBy = GetOrderByMethod();
        ThenBy = GetThenByMethod();
        OrderByDescending = GetOrderByDescendingMethod();
        ThenByDescending = GetThenByDescendingMethod();
    }

    public static MethodInfo OrderBy
    {
        get;
        private set;
    }

    public static MethodInfo ThenBy
    {
        get;
        private set;
    }

    public static MethodInfo OrderByDescending
    {
        get;
        private set;
    }

    public static MethodInfo ThenByDescending
    {
        get;
        private set;
    }

    private static MethodInfo GetOrderByMethod()
    {
        Expression<Func<IQueryable<object>, IOrderedQueryable<object>>> expr =
            q => q.OrderBy((Expression<Func<object, object>>)null);

        return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
    }

    private static MethodInfo GetThenByMethod()
    {
        Expression<Func<IOrderedQueryable<object>, IOrderedQueryable<object>>> expr =
            q => q.ThenBy((Expression<Func<object, object>>)null);

        return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
    }

    private static MethodInfo GetOrderByDescendingMethod()
    {
        Expression<Func<IQueryable<object>, IOrderedQueryable<object>>> expr =
            q => q.OrderByDescending((Expression<Func<object, object>>)null);

        return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
    }

    private static MethodInfo GetThenByDescendingMethod()
    {
        Expression<Func<IOrderedQueryable<object>, IOrderedQueryable<object>>> expr =
            q => q.ThenByDescending((Expression<Func<object, object>>)null);

        return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
    }
}
于 2013-05-22T14:02:12.117 回答
0

在 EF Core 中,您可以使用以下帮助程序类

public static class OrderBuilder
{
    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> queryable, params Tuple<Expression<Func<TSource, object>>, bool>[] keySelectors)
    {
        if (keySelectors == null || keySelectors.Length == 0) return queryable;

        return keySelectors.Aggregate(queryable, (current, keySelector) => keySelector.Item2 ? current.OrderDescending(keySelector.Item1) : current.Order(keySelector.Item1));
    }

    private static bool IsOrdered<TSource>(this IQueryable<TSource> queryable)
    {
        if (queryable == null) throw new ArgumentNullException(nameof(queryable));

        return queryable.Expression.Type == typeof(IOrderedQueryable<TSource>);
    }

    private static IQueryable<TSource> Order<TSource, TKey>(this IQueryable<TSource> queryable, Expression<Func<TSource, TKey>> keySelector)
    {
        if (!queryable.IsOrdered()) return queryable.OrderBy(keySelector);

        var orderedQuery = queryable as IOrderedQueryable<TSource>;

        return (orderedQuery ?? throw new InvalidOperationException()).ThenBy(keySelector);
    }

    private static IQueryable<TSource> OrderDescending<TSource, TKey>(this IQueryable<TSource> queryable, Expression<Func<TSource, TKey>> keySelector)
    {
        if (!queryable.IsOrdered()) return queryable.OrderByDescending(keySelector);

        var orderedQuery = queryable as IOrderedQueryable<TSource>;
        return (orderedQuery ?? throw new InvalidOperationException()).ThenByDescending(keySelector);
    }
}

然后将其用作.. 下面的示例带有一个名为 Player 的类,该类具有以下成员..(为简洁起见,代码已简化)

 public class Player
 {
    ...

    public string FirstName { get; set; 
    public int GenderTypeId { get; set; } 
    public int PlayingExperience { get; set; }

您可以根据需要组合排序,按性别排序,游戏经验降序(注意元组的真实值)和名字..

    var combinedOrder = new[]
    {
        new Tuple<Expression<Func<Player, object>>, bool>(p => p.GenderTypeId, false),
        new Tuple<Expression<Func<Player, object>>, bool>(p => p.PlayingExperience, true),
        new Tuple<Expression<Func<Player, object>>, bool>(p => p.FirstName, false),
    };

只需按以下顺序执行

        var data = context.Set<Player>()
            .OrderBy(combinedOrder)
            .ToArray();
于 2019-04-01T22:19:21.403 回答