0

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);
Breno Macena
  • 449
  • 8
  • 19
  • I will give a try. Thank you! – Breno Macena Nov 11 '21 at 16:03
  • Unfortunately does not work. By calling query.ApplyOrderBy(new[] { Tuple.Create(nameof(ViewPaymentOrder.PaymentOrderME.RegisterDate), isDescending) }) a got this error: 'RegisterDate' is not a member of type 'Bt.CambioOn.Domain.Entities.ViewPaymentOrder'. Am I Doing something wrong? – Breno Macena Nov 11 '21 at 16:10
  • 1
    Sure you are doing it wrong: ` query.ApplyOrderBy(new[] { Tuple.Create("PaymentOrderME.RegisterDate", isDescending) })` – Svyatoslav Danyliv Nov 11 '21 at 16:18
  • Sorry my friend! I'm kind of stupid sometimes. That works like a charm. Thank you very much! – Breno Macena Nov 11 '21 at 16:25

0 Answers0