Search code examples
c#entity-frameworkreflectionlambdalinq-to-entities

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:

public sealed class User : IdentityUser
{
    #region Constructors

    #endregion

    #region Properties

    [Required]
    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last name")]
    public string LastName { get; set; }

    [ForeignKey("Superior")]
    public string SuperiorId { get; set; }

    public User Superior{ get; set; }

    [NotMapped]
    public string FullName => this.LastName + " " + this.FirstName;

    #endregion
}

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?


Solution

  • You need to nest the Property access methods in the loop and then apply the parameter to the lambda.

    private static Expression<Func<T, object>> ToLambda<T>(string propertyName) {
        var propertyNames = propertyName.Split('.');
        var parameter = Expression.Parameter(typeof(T));
        Expression body = parameter;
        foreach (var propName in propertyNames)
            body = Expression.Property(body, propName);
        return Expression.Lambda<Func<T, object>>(body, parameter);
    }