Can someone explain the syntax for building an Expression
that will OrderBy
a user-specified property on an entity?
This MSDN article goes a long way to helping, but it deals with a simple list of strings, my data set contains my own custom objects.
Code first, explanation later.
IQueryable<T> data = this.Database.ObjectsOfType<T>();
var eachItem = Expression.Parameter(typeof(T), "item");
var propertyToOrderByExpression = Expression.Property(eachItem, propertyName);
var runMe = Expression.Call(
typeof(Queryable),
"OrderBy",
new Type[] { data.ElementType, typeof(IComparable) },
data.Expression,
Expression.Lambda<Func<T,IComparable>>(propertyToOrderByExpression, new ParameterExpression[] { eachItem }));
So, first we get hold of the data as a Queryable object. This has a kind of 'root' Expression property, and we need that.
The eachItem thing is an expression that represents the argument placeholder in a Lambda, the symbol in the goes to, if you will.
Then we make an expression that does the read operation the property name specified by the user in propertyName.
We finally build an expression which does the call to the OrderBy method on the Queryable data. We're saying (in order of argument):
Expression.Call(
[what's the type on which we want to call a method?],
[what's the name of the method we're calling?],
[if this method is generic, what are the types it deals with?],
{
[expression representing the data],
[expression for the lambda using the reader exp + each item exp]
})
The last two are in { } since its actually a param array. I used IComparable since the property could be any type but obviously needs to be comparable to be ordered.
Luke