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

.net c# entity-framework expression-trees linq

Question

I have a mapped table, however after compilation, I may add or delete more columns from the table. I'm trying to think of a linq query that will account for those additional columns. I want to sort in this case using one of those dynamic columns. I currently have this.

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);

The following message is shown when it fails:

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.

Why am I misusing this?

1
1
11/14/2014 10:29:02 PM

Popular Answer

Your code attempts to produce something similarQueryable.OrderBy(queryableData.Expression, ExtValue105 => ExtValue105) I don't see why you would think that would work.

According to my understanding of your inquiry, you must dynamically build a phrase likeattribute => attribute.ExtValue105 you may use it to call after that.OrderBy() .

The code may seem like this (assumingqueryableData 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 utilizequeryableData.Provider.CreateQuery() by hand to avert thedynamic however that would be more difficult to do.

0
11/14/2014 10:40:53 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow