链接IQueryable表达式树

时间:2017-01-14 21:55:32

标签: c# .net entity-framework-6 expression-trees iqueryable

我希望能够动态地为我的查询添加排序:

Expression<Func<IQueryable<MyEntity>, IOrderedQueryable<MyEntity>>> order1 = e => e.OrderBy(x => x.Weight);
Expression<Func<IQueryable<MyEntity>, IOrderedQueryable<MyEntity>>> order2 = e => e.OrderByDescending(x => x.Weight).ThenBy(x => x.Price);
Expression<Func<IQueryable<MyEntity>, IOrderedQueryable<MyEntity>>> order3 = e => e.OrderBy(x => x.Category).ThenBy(x => x.Price);

IQueryable<MyEntity> query = any EF query;

var transformedQuery = query.Transform(order1/order2/order3);

如何实施Transform()

public static IQueryable<T> Transform<T>(this IQueryable<T> query, Expression<Func<IQueryable<T>, IOrderedQueryable<T>>> orderExpr)
{
   // ??????????????????
}

我的问题是我不希望有2个重载用于升序/降序排序。我需要应用任何OrderBy()/OrderByDescending()表达式或它们的组合传递。

1 个答案:

答案 0 :(得分:0)

这是需要表达式树的一种情况。甚至是辅助方法。

Func<IQueryable<MyEntity>, IOrderedQueryable<MyEntity>> order = e => e.OrderBy(x => x.Weight);
IQueryable<MyEntity> query = any EF query;

var transformedQuery = order(query);

这是有效的,因为在查询中传递order时,它本身可以调用带有表达式树的相应Queryable.OrderBy重载。