0

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

我已经多次剖析了我的代码,同时提到了两个都被报告可以工作的 SO 帖子; 没有通用方法“ThenBy”“System.Linq.Queryable”类型上没有通用方法“ThenBy”

无论我做什么,我总是收到错误,即使我将它们的实现直接复制并粘贴到我的代码中

错误:

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

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

4

1 回答 1

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 让我走上正轨。

于 2019-06-27T09:49:59.660 回答