Hi I am trying to use that code to get property User.Email of customer that contains User. but its an object (User of type User) so it throws exception. what should i fix?
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
if (!string.IsNullOrWhiteSpace(SortField))
{
var param = Expression.Parameter(typeof (T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] {q.ElementType, exp.Body.Type};
var mce = Expression.Call(typeof (Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
else
{
return q;
}
}
You need to pass a property path to the function (like "User.Email") and account for that inside, like this
The essential part is
which starts from the expression parameter and builds an accessor for each member specified in the path.