以下是Generic Repository存储OrderBy的方式:
private Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy;
这里的Microsoft的OrderBy采用了一串字段名称(来自Microsoft's Dynamic Linq):
public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source,
string ordering, params object[] values);
这是我们的扩展方法,它将我们的字段数组转换为逗号分隔的OrderBy / ThenBy:
public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source,
ICollection<string> orderBy)
{
return source.OrderBy( String.Join(",", orderBy) );
}
一切正常,但需要将OrderBy附加到原始实体。 我们如何将OrderBy保存在变量中以便稍后附加到该实体?
//Something like
Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = ??
供参考,这里是Microsoft的System.Linq.Dynamic.DynamicQueryable.OrderBy源代码(Scott G's writeup link):
public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source, string ordering, params object[] values)
{
return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
}
public static IQueryable OrderBy(
this IQueryable source, string ordering, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[]
{
Expression.Parameter(source.ElementType, "")
};
ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings)
{
queryExpr = Expression.Call(
typeof(Queryable),
o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr,
Expression.Quote(Expression.Lambda(o.Selector, parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}
答案 0 :(得分:2)
这是你想要的吗?
Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = t => t.OrderBy( String.Join(",", orderBy));