2016-05-19 4 views
1

Comme le titre dit que je suis en train de construire un arbre d'expression pour source.OrderByDescending (cette source, expression, comparateur)Linq Expression Arbre OrderByDescending avec comparateur personnalisé

Ceci est mon code pour générer l'arbre d'expression:

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); 

et la méthode 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); 
} 

Mais chaque fois que je l'appelle lambda.Compile().DynamicInvoke(); et inspectez le résultat, je g et l'erreur suivante:

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.

Une idée de ce que je fais mal? Je me sens comme si je suis proche.

+1

Entity Framework ne peut pas fonctionner avec votre comparateur personnalisé 'NumericStringComparer', par conséquent, "ne peut pas être traduit en une expression de magasin". –

+1

[Méthodes LINQ prises en charge et non prises en charge (LINQ to Entities)] (https://msdn.microsoft.com/fr-fr/library/bb738550 (v = vs.110) .aspx) - ** Méthodes de commande: ** * La plupart des méthodes de commande LINQ sont prises en charge dans LINQ to Entities, ** à l'exception de celles qui acceptent un IComparer **, car le comparateur ne peut pas être traduit dans la source de données. * –

+0

Bien sûr. Gros oubli de ma part. Merci! –

Répondre

3

Un extrait du Supported and Unsupported LINQ Methods (LINQ to Entities) - méthodes de commande section:

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.