Using reflection and expression-trees you can provide parameters and then call OrderBy instead of returning Expression<Func<Task, T>> and then calling OrderBy .
Note that OrderBy is an extension method and is implemented in both the System.Linq.Enumarable and System.Linq.Queryable classes. The former is for linq -to-entities , and the latter is for linq-to-entities . The entity-framework needs a query expression tree in order to translate it into SQL commands. Therefore, we use the implementation of Queryable .
This can be done using the extension method (explanations added as comments):
public static IOrderedQueryable<TSource> OrderBy<TSource>( this IEnumerable<TSource> query, string propertyName) { var entityType = typeof(TSource);
Now you can call this OrderBy overload, like any other overload.
For example:
var cheapestItems = _context.Items.OrderBy("Money").Take(10).ToList();
Which means:
SELECT TOP (10) {coulmn names} FROM [dbo].[Items] AS [Extent1] ORDER BY [Extent1].[Money] ASC
This approach can be used to determine all overloads of the OrderByDescending and OrderByDescending to use the string property selector.
Taher rahgooy
source share