public static class DynamicOrderBy
{
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty,
bool desc) where TEntity : class
{
string command = desc ? "OrderByDescending" : "OrderBy";
var type = typeof(TEntity);
var property = type.GetProperty(orderByProperty);
var parameter = System.Linq.Expressions.Expression.Parameter(type, "p");
var propertyAccess = System.Linq.Expressions.Expression.MakeMemberAccess(parameter, property);
var orderByExpression = System.Linq.Expressions.Expression.Lambda(propertyAccess, parameter);
var resultExpression =
System.Linq.Expressions.Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
source.Expression, System.Linq.Expressions.Expression.Quote(orderByExpression));
return source.Provider.CreateQuery<TEntity>(resultExpression);
}
reference :
Hiç yorum yok:
Yorum Gönder