EntityFramework LINQ Order using string and nested

2019-08-22 07:22发布

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?

2条回答
戒情不戒烟
2楼-- · 2019-08-22 07:27

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);
}
查看更多
爷的心禁止访问
3楼-- · 2019-08-22 07:36

I once wrote a extention method for IQueryables to sort by a property defined by string:

public static IOrderedQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    else
    {

        if (propertyName.EndsWith(" ASC", StringComparison.OrdinalIgnoreCase))
            propertyName = propertyName.Replace(" ASC", "");

        // DataSource control passes the sort parameter with a direction
        // if the direction is descending           
        int descIndex = propertyName.IndexOf(" DESC", StringComparison.OrdinalIgnoreCase);
        if (descIndex >= 0)
        {
            propertyName = propertyName.Substring(0, descIndex).Trim();
        }

        ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
        MemberExpression property = Expression.Property(parameter, propertyName);
        LambdaExpression lambda = Expression.Lambda(property, parameter);

        string methodName = (descIndex < 0) ? "OrderBy" : "OrderByDescending";

        Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
                                                                                new Type[] { source.ElementType, property.Type },
                                                                                source.Expression, Expression.Quote(lambda));

        return source.Provider.CreateQuery<T>(methodCallExpression) as IOrderedQueryable<T>;
    }
}

You may call then LIST.AsQueryable().SortBy("Surname").

查看更多
登录 后发表回答