我喜欢@Mark Powell的回答,但正如@ShuberFu所说,它给出了错误LINQ to Entities only supports casting EDM primitive or enumeration types
。
删除var propAsObject = Expression.Convert(property, typeof(object));
不适用于值类型的属性(例如整数),因为它不会将int隐式装到对象中。
通过使用Kristofer Andersson和Marc Gravell的Ideas,我找到了一种使用属性名称构造Queryable函数并使它仍可与Entity Framework一起使用的方法。我还包括一个可选的IComparer参数。警告: IComparer参数不适用于Entity Framework,如果使用Linq to Sql,则应将其忽略。
以下与Entity Framework和Linq to Sql一起使用:
query = query.OrderBy("ProductId");
而@Simon Scheurer这也适用:
query = query.OrderBy("ProductCategory.CategoryId");
而且,如果您没有使用Entity Framework或Linq to Sql,则可以这样做:
query = query.OrderBy("ProductCategory", comparer);
这是代码:
public static class IQueryableExtensions
{
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string propertyName, IComparer<object> comparer = null)
{
return CallOrderedQueryable(query, "OrderBy", propertyName, comparer);
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> query, string propertyName, IComparer<object> comparer = null)
{
return CallOrderedQueryable(query, "OrderByDescending", propertyName, comparer);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> query, string propertyName, IComparer<object> comparer = null)
{
return CallOrderedQueryable(query, "ThenBy", propertyName, comparer);
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> query, string propertyName, IComparer<object> comparer = null)
{
return CallOrderedQueryable(query, "ThenByDescending", propertyName, comparer);
}
public static IOrderedQueryable<T> CallOrderedQueryable<T>(this IQueryable<T> query, string methodName, string propertyName,
IComparer<object> comparer = null)
{
var param = Expression.Parameter(typeof(T), "x");
var body = propertyName.Split('.').Aggregate<string, Expression>(param, Expression.PropertyOrField);
return comparer != null
? (IOrderedQueryable<T>)query.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
methodName,
new[] { typeof(T), body.Type },
query.Expression,
Expression.Lambda(body, param),
Expression.Constant(comparer)
)
)
: (IOrderedQueryable<T>)query.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
methodName,
new[] { typeof(T), body.Type },
query.Expression,
Expression.Lambda(body, param)
)
);
}
}