我正在尝试为 IQueryable 创建一个扩展方法,该方法通过对象的任意属性对其进行排序。
public static class IQueryableExtender
{
public static IQueryable<TSource> Sort<TSource>(this IQueryable<TSource> query, string orderProperty, string sortDirection = "asc")
{
var elementType = query.ElementType;
var propertyInfo = elementType.GetProperty(orderProperty);
if (propertyInfo == null)
{
throw new ArgumentException(string.Format("{0} is not a property on {1}", orderProperty, elementType.Name));
}
switch (sortDirection.ToLower())
{
case "asc":
case "ascending":
return query.OrderBy(x => propertyInfo.GetValue(x, null));
break;
case "desc":
case "descending":
return query.OrderByDescending(x => propertyInfo.GetValue(x, null));
break;
}
return query;
}
}
调用该方法时出现此错误。我想这与 IQueryable 尚未执行和检索任何对象有关。
LINQ to Entities 无法识别该方法System.Object GetValue(System.Object, System.Object[])
,并且该方法无法转换为存储表达式。
我可以通过在 IQueryable 上执行 ToList 来解决它,但是然后我在扩展方法中检索数据,这不是我想要的。
这可以解决吗?