How to check for the presence of an OrderBy in a ObjectQuery expression tree

后端 未结 6 1039
礼貌的吻别
礼貌的吻别 2020-12-09 07:09

I\'m using T4 for generating repositories for LINQ to Entities entities.

The repository contains (amongst other things) a List method suitable for paging. The docum

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 07:18

    Paging depends on Ordering in a strong way. Why not tightly couple the operations? Here's one way to do that:

    Support objects

    public interface IOrderByExpression
    {
      ApplyOrdering(ref IQueryable query);
    }
    
    public class OrderByExpression : IOrderByExpression
    {
      public IQueryable ApplyOrderBy(ref IQueryable query)
      {
        query = query.OrderBy(exp);
      }
      //TODO OrderByDescending, ThenBy, ThenByDescending methods.
    
      private Expression> exp = null;
    
      //TODO bool descending?
      public OrderByExpression (Expression> myExpression)
      {
        exp = myExpression;
      }
    }
    

    The method under discussion:

    public IQueryable List(int startIndex, int count, IOrderByExpression ordering)
    {
        NorthwindEntities ent = new NorthwindEntities();
        IQueryable query = ent.Categories;
        if (ordering == null)
        {
          ordering = new OrderByExpression(c => c.CategoryID)
        }
        ordering.ApplyOrdering(ref query);
    
        return query.Skip(startIndex).Take(count);
    }
    

    Some time later, calling the method:

    var query = List(20, 20, new OrderByExpression(c => c.CategoryName));
    

提交回复
热议问题