无法在LINQ OrderBy中使用属性名进行排序

错误是

LINQ to Entities无法识别方法’System.Object GetValue(System.Object,System.Object [])’方法,并且此方法无法转换为存储表达式。

我的代码是

public static GridResult GetAllUsers(int count, int tblsize,string sortcreteria) { using (UserEntities entity = new UserEntities()) { var data = entity.User_Details.Take(count) .OrderBy(i =>.GetType().GetProperty(sortcreteria).GetValue(i,null)) .Skip(tblsize).ToList(); result.DataSource = data; result.Count = entity.User_Details.Count(); } return result; } 

如何使用属性名称作为字符串排序?

只需在代码中添加以下扩展名即可:

 using System.Linq; using System.Linq.Expressions; using System; namespace SomeNameSpace { public static class SomeExtensionClass { public static IQueryable OrderByField(this IQueryable q, string SortField, bool Ascending) { var param = Expression.Parameter(typeof(T), "p"); var prop = Expression.Property(param, SortField); var exp = Expression.Lambda(prop, param); string method = Ascending ? "OrderBy" : "OrderByDescending"; Type[] types = new Type[] { q.ElementType, exp.Body.Type }; var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp); return q.Provider.CreateQuery(mce); } } 

}

用法:

 .OrderByField(sortcriteria, true) 

编辑:

但是为了支持ThenBy方法,返回IOrderedQueryable的以下方法应该完成所有操作:

 public static class SomeExtensionClass { private static IOrderedQueryable OrderingHelper(IQueryable source, string propertyName, bool descending, bool anotherLevel) { var param = Expression.Parameter(typeof(T), "p"); var property = Expression.PropertyOrField(param, propertyName); var sort = Expression.Lambda(property, param); var call = Expression.Call( typeof(Queryable), (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty), new[] { typeof(T), property.Type }, source.Expression, Expression.Quote(sort)); return (IOrderedQueryable)source.Provider.CreateQuery(call); } public static IOrderedQueryable OrderBy(this IQueryable source, string propertyName) { return OrderingHelper(source, propertyName, false, false); } public static IOrderedQueryable OrderBy(this IQueryable source, string propertyName, bool descending) { return OrderingHelper(source, propertyName, descending, false); } public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string propertyName) { return OrderingHelper(source, propertyName, false, true); } public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string propertyName, bool descending) { return OrderingHelper(source, propertyName, descending, true); } } 

您可以尝试使用(有点旧的) 动态LINQ库来执行此操作:

 var data = entity.User_Details .Take(count) .OrderBy(sortcriteria) .Skip(tblsize) .ToList(); 

或者,您仍然可以通过首先将对象移动到内存中来使用原始查询对序列进行排序,因为LINQ to Entities提供程序无法将对Reflection API的调用转换为SQL:

 var data = entity.User_Details .Take(count) .Skip(tblsize) .AsEnumerable() .OrderBy(i => i.GetType().GetProperty(sortcriteria).GetValue(i, null)) 

您可能需要使用Expression Trees来构造Linq语句OrderBy(x => x.SomeProperty)

为LINQ / Lambda创建一个OrderBy表达式

动态创建LINQ到实体OrderBy表达式