0

I have the following code:

public IOrderedQueryable<T> CreateOrderedList<T>(IQueryable<T> items, string orderByprop, string descProperty)
{
    if (!string.IsNullOrEmpty(orderByprop) && !string.IsNullOrEmpty(descProperty))
    {
        return items.OrderedList(orderByprop, descProperty == "desc");                    
    }
    return (IOrderedQueryable<T>)items;
}

public static IOrderedQueryable<T> OrderedList<T>(this IQueryable<T> items, string filterProperty, bool descending = false)
{
    var propertyInfo = typeof(T).GetProperty(filterProperty ?? string.Empty, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    if (propertyInfo == null)
    {
        throw new Exception("Value not found on T");
    }

    dynamic OrderBy(T o) => propertyInfo.GetValue(o, null);
    return (descending ? (IOrderedQueryable<T>)items.OrderByDescending(OrderBy) : (IOrderedQueryable<T>)items.OrderBy(OrderBy));
}

When I try to execute this, it gives me the following error :

Can't convert object of type System.Linq.OrderedEnumerable`2[Logic.Models.CRM.Project,System.Object] to object of type System.Linq.IOrderedQueryable`1[Logic.Models.CRM.Project].

I however chaining more code to the query (filtering of data), so I need the object to stay an IQueryable, so that the query materializes later. How can I implement this functionality?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Kai
  • 732
  • 1
  • 7
  • 23
  • 1
    Check [this](https://stackoverflow.com/q/34906437/4685428) question. It looks like you should build an expression tree manually – Aleks Andreev Dec 06 '18 at 16:11

2 Answers2

0

Try the following :

return descending ? items.Cast<T>.OrderByDescending(OrderBy) 
                  :items.Cast<T>.OrderBy(OrderBy)
eran otzap
  • 12,293
  • 20
  • 84
  • 139
0

I've solved my problem and there was only one small change required:

dynamic OrderBy(T o) => propertyInfo.GetValue(o, null);

should have been

Expression<Func<T, dynamic>> orderBy = o => propertyInfo.GetValue(o, null);

Because I used a delegate instead of an expression, this must've forced .NET to materialize the query instead of extending the expression

Kai
  • 732
  • 1
  • 7
  • 23