mardi 20 février 2018

EntityFramework LINQ Order using string and nested reflection

I saw already some of the similar questions, but cannot find an anwser how to solve this problem.
I want to have a possibility to order collection using string as property name.

Model:

User { string FullName; User SuperiorUser }

And I want to make a call like this:

DbSet.Order("SuperiorUser.FullName", Asc/Desc)...

My below functions work for a Order("FullName", Asc/Desc), but dont when I want to go deeper.

public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName,
    ListSortDirection direction = ListSortDirection.Ascending)
{
    return ListSortDirection.Ascending == direction
        ? source.OrderBy(ToLambda<T>(propertyName))
        : source.OrderByDescending(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);

    return Expression.Lambda<Func<T, object>>(property, parameter);
}

So I made it look a little bit like this

private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
    var propertyNames = propertyName.Split('.');
    var type = typeof(T)
    ParameterExpression parameter;
    MemberExpression property;
    for (var propName in propertyNames)
    {
        parameter = Expression.Parameter(type);
        property = Expression.Property(parameter, propName);
        type = property.Type;
    }
    return Expression.Lambda<Func<T, object>>(property, parameter);
}

But this unfortunately returns error The parameter '' was not bound in the specified LINQ to Entities query expression. What am I missing?





Aucun commentaire:

Enregistrer un commentaire