正如标题所说,我正在尝试为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无法识别方法'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])'方法,此方法无法翻译进入商店表达。
知道我做错了什么吗?我觉得我很亲密。
答案 0 :(得分:3)
摘自Supported and Unsupported LINQ Methods (LINQ to Entities) - 订购方法部分:
LINQ to Entities支持大多数LINQ排序方法,除了那些接受IComparer&lt; T&gt; 的LINQ排序方法,因为比较器无法转换为数据源。