public static class EntityQueryExtensions { public static IEntityQuery<TSource> Order<TSource>(this IQueryable<TSource> source, string property, ListSortDirection listSortDirection) { if (listSortDirection == ListSortDirection.Ascending) { return ApplyOrder(source, property, "OrderBy"); } // Descending return ApplyOrder(source, property, "OrderByDescending"); }
public static IEntityQuery<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string property) { return ApplyOrder(source, property, "OrderBy"); }
public static IEntityQuery<TSource> OrderByDescending<TSource>(this IQueryable<TSource> source, string property) { return ApplyOrder(source, property, "OrderByDescending"); }
public static IEntityQuery<TSource> ThenBy<TSource>(this IQueryable<TSource> source, string property) { return ApplyOrder(source, property, "ThenBy"); }
public static IEntityQuery<TSource> ThenByDescending<TSource>(this IQueryable<TSource> source, string property) { return ApplyOrder(source, property, "ThenByDescending"); }
public static IEntityQuery<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) { ParameterExpression arg = Expression.Parameter(typeof(T), property); Expression expr = arg;
foreach (string prop in property.Split('.')) { // use reflection (not ComponentModel) to mirror LINQ expr = Expression.PropertyOrField(expr, prop); }
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), expr.Type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
return (IEntityQuery<T>)
typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2).MakeGenericMethod(typeof(T), expr.Type) .Invoke(null, new object[] { source, lambda }); } }
|