【问题标题】:Dynamic OrderBy // InvalidOperationException: No generic method 'ThenByDescending' on type 'System.Linq.Queryable' is compatibleDynamic OrderBy // InvalidOperationException:不兼容类型“System.Linq.Queryable”的通用方法“ThenByDescending”
【发布时间】:2019-11-08 17:20:21
【问题描述】:

我正在尝试构建一个可以重复调用的动态 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;
}

如果有人能对此有所了解,将不胜感激,我已经把头发扯了三个多小时了!

【问题讨论】:

  • 您好,您可以发布一个调用上述方法并重现问题的小代码 sn-p 吗?我问是因为该方法的代码看起来不错。
  • @IvanStoev 我已经添加了调用代码,感谢您抽出宝贵时间。

标签: c# linq expression iqueryable iorderedqueryable


【解决方案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 让我走上正轨。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多