Linq to Sql – 存储库模式 – 动态OrderBy

前端之家收集整理的这篇文章主要介绍了Linq to Sql – 存储库模式 – 动态OrderBy前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好的,我找到了 this,这将允许我这样做:
  1. public IList<Item> GetItems(string orderbyColumn)
  2. {
  3. return _repository.GetItems().OrderBy(orderByColumn).ToList();
  4. }

这是进行“动态”排序的最佳方式吗?我希望能够将列名作为字符串(和排序方向)传递给我的服务,并让它以正确的方式排序.

解决方法

如果您只是在动态排序之后没有完整的Dynamic-Linq内容,您可以查看我之前写的一篇文章click

编辑:我不再博客了,所以这里是实际的扩展方法

  1. public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source,string sortExpression) where TEntity : class
  2. {
  3. if (string.IsNullOrEmpty(sortExpression))
  4. return source; // nothing to sort on
  5.  
  6. var entityType = typeof(TEntity);
  7. string ascSortMethodName = "OrderBy";
  8. string descSortMethodName = "OrderByDescending";
  9. string[] sortExpressionParts = sortExpression.Split(' ');
  10. string sortProperty = sortExpressionParts[0];
  11. string sortMethod = ascSortMethodName;
  12.  
  13. if (sortExpressionParts.Length > 1 && sortExpressionParts[1] == "DESC")
  14. sortMethod = descSortMethodName;
  15.  
  16. var property = entityType.GetProperty(sortProperty);
  17. var parameter = Expression.Parameter(entityType,"p");
  18. var propertyAccess = Expression.MakeMemberAccess(parameter,property);
  19. var orderByExp = Expression.Lambda(propertyAccess,parameter);
  20.  
  21. MethodCallExpression resultExp = Expression.Call(
  22. typeof(Queryable),sortMethod,new Type[] { entityType,property.PropertyType },source.Expression,Expression.Quote(orderByExp));
  23.  
  24. return source.Provider.CreateQuery<TEntity>(resultExp);
  25. }

猜你在找的MsSQL相关文章