Linq to Sql-存储库模式-动态OrderBy [英] Linq to Sql - Repository Pattern - Dynamic OrderBy
本文介绍了Linq to Sql-存储库模式-动态OrderBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ok, I found this, which will allow me to do this:
public IList<Item> GetItems(string orderbyColumn)
{
return _repository.GetItems().OrderBy(orderByColumn).ToList();
}
这是执行动态"订购的最佳方法吗?我希望能够将列名作为字符串(以及排序方向)传递给我的服务,并以正确的方式进行排序.
Is this the best way to do "dynamic" ordering? I want to be able to pass the column name as a string (and the sort direction) to my Service, and have it order the correct way.
推荐答案
如果您只是在没有完整的Dynamic-Linq内容的情况下进行动态排序,则可以查看我前一段时间写过的帖子:单击
If you're just after dynamic sorting without the full Dynamic-Linq stuff you can check out a post I wrote about this a while back: click
我真的不再写博客了,所以这里是实际的扩展方法:
I don't really blog anymore so here's the actual extension method:
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);
}
这篇关于Linq to Sql-存储库模式-动态OrderBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文