-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryableExtensions.cs
34 lines (27 loc) · 1.52 KB
/
QueryableExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System.Linq.Expressions;
namespace EntityFrameworkLibrary;
/// <summary>
/// Extension methods to perform Order By using strings
/// </summary>
public static class QueryableExtensions
{
public static IOrderedQueryable<T> OrderByColumn<T>(this IQueryable<T> source, string columnPath)
=> source.OrderByColumnUsing(columnPath, "OrderBy");
public static IOrderedQueryable<T> OrderByColumnDescending<T>(this IQueryable<T> source, string columnPath)
=> source.OrderByColumnUsing(columnPath, "OrderByDescending");
public static IOrderedQueryable<T> ThenByColumn<T>(this IOrderedQueryable<T> source, string columnPath)
=> source.OrderByColumnUsing(columnPath, "ThenBy");
public static IOrderedQueryable<T> ThenByColumnDescending<T>(this IOrderedQueryable<T> source, string columnPath)
=> source.OrderByColumnUsing(columnPath, "ThenByDescending");
private static IOrderedQueryable<T> OrderByColumnUsing<T>(this IQueryable<T> source, string columnPath, string method)
{
var parameter = Expression.Parameter(typeof(T), "item");
var member = columnPath.Split('.')
.Aggregate((Expression)parameter, Expression.PropertyOrField);
var keySelector = Expression.Lambda(member, parameter);
var methodCall = Expression.Call(typeof(Queryable), method, new[]
{ parameter.Type, member.Type },
source.Expression, Expression.Quote(keySelector));
return (IOrderedQueryable<T>)source.Provider.CreateQuery(methodCall);
}
}