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

好的,我找到了 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);
    }

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...