Linq to Sql – 存储库模式 – 动态OrderBy
发布时间:2020-12-12 16:26:56 所属栏目:MsSql教程 来源:网络整理
导读:好的,我找到了 this,这将允许我这样做: public IListItem GetItems(string orderbyColumn){ return _repository.GetItems().OrderBy(orderByColumn).ToList();} 这是进行“动态”排序的最佳方式吗?我希望能够将列名作为字符串(和排序方向)传递给我的服务,并
好的,我找到了
this,这将允许我这样做:
public IList<Item> GetItems(string orderbyColumn) { return _repository.GetItems().OrderBy(orderByColumn).ToList(); } 这是进行“动态”排序的最佳方式吗?我希望能够将列名作为字符串(和排序方向)传递给我的服务,并让它以正确的方式排序. 解决方法如果您只是在动态排序之后没有完整的Dynamic-Linq内容,您可以查看我之前写的一篇文章: click编辑:我不再博客了,所以这里是实际的扩展方法: public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source,string sortExpression) where TEntity : class { if (string.IsNullOrEmpty(sortExpression)) return source; // nothing to sort on var entityType = typeof(TEntity); string ascSortMethodName = "OrderBy"; string descSortMethodName = "OrderByDescending"; string[] sortExpressionParts = sortExpression.Split(' '); string sortProperty = sortExpressionParts[0]; string sortMethod = ascSortMethodName; if (sortExpressionParts.Length > 1 && sortExpressionParts[1] == "DESC") sortMethod = descSortMethodName; var property = entityType.GetProperty(sortProperty); var parameter = Expression.Parameter(entityType,"p"); var propertyAccess = Expression.MakeMemberAccess(parameter,property); var orderByExp = Expression.Lambda(propertyAccess,parameter); MethodCallExpression resultExp = Expression.Call( typeof(Queryable),sortMethod,new Type[] { entityType,property.PropertyType },source.Expression,Expression.Quote(orderByExp)); return source.Provider.CreateQuery<TEntity>(resultExp); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |