Using expression trees to create a custom order by

2019-08-15 01:40发布

问题:

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?

回答1:

Is queryableData of type IQueryable<DateTime>? Seems not to be since you are calling CreateQuery<string>.

Your call to Expression.Call seems to assume that this is an IQueryable<DateTime>. Make sure that it is.

You can find out how to correctly build a LINQ query by hard-coding the query and then decompiling the resulting assembly.



回答2:

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.