I'm trying to build an extension method to IQueryable which can sort a collection by entity child property.
I have the following class:
public class ViewPaymentOrder : Entity
{
public string ClientName { get; set; }
// ... other properties
public PaymentOrderME PaymentOrderME { get; set; }
}
And I need to sort by PaymentOrderME.RegisterDate
.
I have this function that works fine to sort by ViewPaymentOrder
properties:
public static IQueryable<T> OrderByField<T>(this IQueryable<T> source, string field, bool isDescending = true)
{
var type = typeof(T);
var property = type.GetProperty(field);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var arguments = Expression.Lambda(propertyAccess, parameter);
var resultExp = Expression.Call(typeof(Queryable),
isDescending ? "OrderByDescending" : "OrderBy",
new[] { type, property.PropertyType },
source.Expression, arguments);
return source.Provider.CreateQuery<T>(resultExp);
}
For example, by calling
IQueryable<ViewPaymentOrder> query;
//...
query.OrderByField(nameof(ViewPaymentOrder.ClientName), isDescending);
It sort perfectly.
How can I adapt this function to be able to sort by PaymentOrderME
class properties?
Something like this
IQueryable<ViewPaymentOrder> query;
//...
query.OrderByField(nameof(ViewPaymentOrder.PaymentOrderME.RegisterDate), isDescending);