Entity Framework 4、5 多字段排序

public interface IOrderByExpression<TEntity> where TEntity : class
{
    IOrderedQueryable<TEntity> ApplyOrderBy(IQueryable<TEntity> query);
    IOrderedQueryable<TEntity> ApplyThenBy(IOrderedQueryable<TEntity> query);
}

public class OrderByExpression<TEntity, TOrderBy> : IOrderByExpression<TEntity>
    where TEntity : class
{
    private Expression<Func<TEntity, TOrderBy>> _expression;
    private bool _descending;

    public OrderByExpression(Expression<Func<TEntity, TOrderBy>> expression,
        bool descending = false)
    {
        _expression = expression;
        _descending = descending;
    }

    public IOrderedQueryable<TEntity> ApplyOrderBy(
        IQueryable<TEntity> query)
    {
        if (_descending)
            return query.OrderByDescending(_expression);
        else
            return query.OrderBy(_expression);
    }

    public IOrderedQueryable<TEntity> ApplyThenBy(
        IOrderedQueryable<TEntity> query)
    {
        if (_descending)
            return query.ThenByDescending(_expression);
        else
            return query.ThenBy(_expression);
    }
}


 

 调用方法

public static class IQueryableHelper
{
        /// <summary>
        /// IQueryable 接口的多字段排序 请在执行底层时使用
        /// </summary>
        /// <typeparam name="TEntity">目标类型</typeparam>
        /// <param name="query"></param>
        /// <param name="orderByExpressions"></param>
        /// <returns></returns>
        public static IQueryable<TEntity> ApplyOrderBy<TEntity>(this IQueryable<TEntity> query,
   params IOrderByExpression<TEntity>[] orderByExpressions)
   where TEntity : class
        {
            if (orderByExpressions == null)
                return query;
            IOrderedQueryable<TEntity> output = null;

            foreach (var orderByExpression in orderByExpressions)
            {
                if (output == null)//检查是否是第一次
                    output = orderByExpression.ApplyOrderBy(query);
                else
                    output = orderByExpression.ApplyThenBy(output);
            }

            return output ?? query;
        }
}

调用处

 using (var db = ConnectionHelper.GetConn())
            {
                var list = db.tb_Store.ApplyOrderBy(new OrderByExpression<tb_Store, string>(u => u.StorePhone),
                      new OrderByExpression<tb_Store, string>(u => u.StoreCode, true)
                      ).Skip(skip).Take(take);//用自己写的扩展方法代替原来的orderby 
                var xx = ((ObjectQuery)list).ToTraceString(); //这里可以看一下生成的sql语句 
            }

 

posted @ 2015-03-30 14:07  xingbo  阅读(344)  评论(0编辑  收藏  举报