Using expression trees to create a custom order by in linq to entities

.net c# entity-framework expression-trees linq

Question

I have a table that's mapped, but after compile additional columns can be added or removed from the table. I'm trying to come up with a linq query that will take those new columns into account. In this scenario, I want to order by one of those dynamic columns. This is what I have so far.

var queryableData = dc.wf_task_ext_attributes.AsQueryable();
ParameterExpression pe = Expression.Parameter(typeof(DateTime), "ExtValue105");

// The next line is where it fails
MethodCallExpression orderByCallExpression = Expression.Call(
      typeof(Queryable),
       "OrderBy",
       new Type[] { queryableData.ElementType, queryableData.ElementType },
       queryableData.Expression,
       Expression.Lambda<Func<DateTime, DateTime>>(pe, new ParameterExpression[] { pe }));

IQueryable<string> results = queryableData.Provider.CreateQuery<string>
                         (orderByCallExpression);

It's failing with the following message:

No generic method 'OrderBy' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

What am I doing wrong?

Popular Answer

Your code tries to create something like Queryable.OrderBy(queryableData.Expression, ExtValue105 => ExtValue105). I have no idea why would you expect that to work.

If I understand your question correctly, you need to dynamically create an expression like attribute => attribute.ExtValue105 and then you can use that to call OrderBy().

The code could look something like this (assuming queryableData is IQueryable<Attribute>):

var parameter = Expression.Parameter(typeof(Attribute), "attribute");
var property = Expression.Property(parameter, "ExtValue105");
var lambda = Expression.Lambda(property, parameter);

IQueryable<Attribute> results =
    Queryable.OrderBy(queryableData, (dynamic)lambda);

You could use queryableData.Provider.CreateQuery() manually to avoid the dynamic call, but that would be more complicated.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why