IMongoQueryable OrderBy 动态 属性 名称

IMongoQueryable OrderBy dynamic Property Name

我正在尝试使用 属性 字符串通过反射来订购我的 IMongoqueryable 集合。

很遗憾,我收到消息 Only fields are allowed in a $sort.

private static void SetOrderBy(ref IMongoQueryable<Trade> trades, BlazorGridRequest request)
{
    var prop = typeof(Trade).GetProperty(request.OrderBy);

    if (request.OrderByDescending)
        trades = trades.OrderByDescending(t => prop.GetValue(t));
    else
        trades = trades.OrderBy(t => prop.GetValue(t));
}

谁能帮我弄清楚,我怎样才能让它工作? 谢谢!

感谢 dododo 的评论,我找到了以下解决方案:

private static void SetOrderBy(ref IMongoQueryable<Trade> trades, BlazorGridRequest request)
{
    ParameterExpression pe = Expression.Parameter(typeof(Trade), "t");
    MemberExpression me = Expression.Property(pe, request.OrderBy);
    Expression conversion = Expression.Convert(me, typeof(object));
    Expression<Func<Trade, object>> orderExpression = Expression.Lambda<Func<Trade, object>> (conversion, new[] { pe });

    if (request.OrderByDescending)
        trades = trades.OrderByDescending(orderExpression);
    else
        trades = trades.OrderBy(orderExpression);
}