动态OrderBy // InvalidOperationException:类型'System.Linq.Queryable'上的通用方法'ThenByDescending'不兼容

时间:2019-06-26 17:31:55

标签: c# linq expression iqueryable iorderedqueryable

我正在尝试构建一个可以重复调用的动态OrderBy方法,不幸的是,尽管实现了已报告的可修复该错误的代码,但我仍然遇到相同的错误。

我已经多次剖析了我的代码,同时提到了两个据报道都可以正常工作的SO帖子; No generic method 'ThenBy'No generic method 'ThenBy' on type 'System.Linq.Queryable'

无论我做什么,即使我将其实现直接复制并粘贴到我的代码中,也始终会收到错误消息

错误:

InvalidOperationException:

No generic method 'ThenByDescending' on type 'System.Linq.Queryable' is compatible
with the supplied type arguments and arguments.

No type arguments should be provided if the method is non-generic.

我的方法:

public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IOrderedQueryable<TEntity> source, string orderByProperty, bool desc, bool then)
{
    var command = (then ? "Then" : "Order") + (desc ? "ByDescending" : "By");

    var entityType = typeof(TEntity);
    var entityParameter = Expression.Parameter(entityType, "x");

    var property = entityType.GetProperty(orderByProperty);

    var propertyAccess = Expression.MakeMemberAccess(entityParameter, property);
    var orderByExpression = Expression.Lambda(propertyAccess, entityParameter);

    var resultExpression =
        Expression.Call(typeof(Queryable), command, new Type[] { entityType, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));

    return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}

呼叫方式

public IQueryable<T> SortQuery(IQueryable<T> query, Dictionary<string, char> sorts, Dictionary<string, string> sortableProperties)
{
    var count = 0;

    foreach (var s in sorts)
        if (!string.IsNullOrWhiteSpace(s.Key) && new[] {'A', 'D'}.Contains(char.ToUpper(s.Value)))
            query = ((IOrderedQueryable<T>)query).OrderBy(sortableProperties[s.Key], char.ToUpper(s.Value) == 'D', count++ == 0);

    return query;
}

如果有人可以对此有所了解,将不胜感激,我已经把头发扯了超过3个小时!

1 个答案:

答案 0 :(得分:1)

破解它,问题在于传递的Queryable只是一个IQueryable,而不是IOrderedQueryable-投放无效,它必须是IOrderedQueryable。

public IOrderedQueryable<T> SortQuery(IQueryable<T> query, Dictionary<string, char> sorts)
{
    var count = 0;

    var orderedQuery = query.OrderBy(x => true); // This is the fix!

    foreach (var s in sorts)
        if (!string.IsNullOrWhiteSpace(s.Key) && new[] {'A', 'D'}.Contains(char.ToUpper(s.Value)))
            orderedQuery = orderedQuery.OrderBy(this.SortFields[s.Key], char.ToUpper(s.Value) == 'D', count++ == 0);

    return orderedQuery;
}

赞扬@IvanStoev将我设置在正确的轨道上。