2016-05-19 9 views
1

とLINQの式ツリーOrderByDescendingタイトルは私が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();を呼び出し、その結果を点検したときに、I G次のエラーがあります。

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.

私は間違っていますか?私はかなり近いと感じる。

+1

エンティティフレームワークは、カスタム比較演算 'NumericStringComparer'で作業することはできませんが、それゆえ「ストア式に変換することができません」。 –

+1

[サポートされているLINQメソッドとサポートされていないLINQメソッド(LINQ to Entities)](** https://msdn.microsoft.com/en-us/library/bb738550(v = vs.110).aspx) - **注文方法:** *ほとんどのLINQ順序付け方法は、LINQ to Entitiesでサポートされています。ただし、Compareerをデータソースに変換できないため、IComparer **を受け付けるものを除きます。* –

+0

もちろんです。私のところで大きな見落とし。ありがとう! –

答えて

3

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.

関連する問題