我正在尝试构建一个可以重复调用的动态 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;
}
如果有人能对此有所了解,将不胜感激,我已经把头发扯了三个多小时了!