Linq 表达式树 OrderByDescending 与自定义比较器

Linq Expression Tree OrderByDescending with custom comparer

正如标题所说,我正在尝试为 source.OrderByDescending(此源、表达式、比较器)

构建一个表达式树

这是我生成表达式树的代码:

var orderByDescendingMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).First(m => m.Name == "OrderByDescending" && m.GetParameters().Count() == 3).MakeGenericMethod(typeof(Books), typeof(string));
var comparer = Expression.New(typeof(NumericStringComparer));
var orderByFilter = GenerateOrderByPropertyExpression<string>(propertyName);
var comparison = Expression.Call(orderByDescendingMethod, Expression.Constant(books), orderByFilter, comparer);

return Expression.Lambda(comparison);

以及 GenerateOrderByPropertyExpression 方法:

private static Expression<Func<Books, T>> GenerateOrderByPropertyExpression<T>(string propertyName)
{
    var parameter = Expression.Parameter(typeof(Books), "b");
    var property = Expression.Property(parameter, propertyName);
    var toStringMethod = typeof(object).GetMethod("ToString");
    var objectString = Expression.Call(property, toStringMethod);

    return Expression.Lambda<Func<Books, T>>(objectString, parameter);
}

但是每当我调用 lambda.Compile().DynamicInvoke(); 并检查结果时,我都会收到以下错误:

LINQ to Entities does not recognize the method 'System.Linq.IOrderedQueryable`1[DataAccess.Plusbog.Books] OrderByDescending[Books,String](System.Linq.IQueryable`1[DataAccess.Plusbog.Books], System.Linq.Expressions.Expression`1[System.Func`2[DataAccess.Plusbog.Books,System.String]], System.Collections.Generic.IComparer`1[System.String])' method, and this method cannot be translated into a store expression.

知道我做错了什么吗?我觉得我已经很接近了。

摘自 Supported and Unsupported LINQ Methods (LINQ to Entities) - 订购方法 部分:

Most of the LINQ ordering methods are supported in LINQ to Entities, with the exception of those that accept an IComparer<T>, because the comparer cannot be translated to the data source.