I would kindly ask you for help.
When I have queryable such as
var query = dbSet.AsQueryable();
and I would like to dynamicly set orderBy using reflection
var orderBy = "School.Name"
query = query.OrderBy("School.Name");
var data = await query.ToListAsync()
I do have extension to support order like this using reflection as following:
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
return source.OrderBy(ToLambda<T>(propertyName));
}
private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
var parameter = Expression.Parameter(typeof(T));
var property = Expression.Property(parameter, propertyName);
var propAsObject = Expression.Convert(property, typeof(object));
return Expression.Lambda<Func<T, object>>(propAsObject, parameter);
}
Problem is to create lambda for inner object property such as School.Name. This solution works for Name attribute on Dbset object, but not on joinned.
Goal is to modify ToLambda method to support joinned or inners properties.
using
query.OrderBy("School.Name");
// instead of
query.OrderBy(m => m.School.Name );
Thanks for your help.
Aucun commentaire:
Enregistrer un commentaire