代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

实体框架4:如何将字符串转换为.OrderBy(p=>p.fieldname)的对象?

  •  2
  • Zachary Scott  · 技术社区  · 14 年前

    不能 执行以下操作:

    var a = myDB.Where(p => p.field == "filter").OrderBy("it." + fieldname);
    

    如何将“productID,productName”之类的字符串转换为OrderBy表达式 ? 如果我的想法是正确的,那么问题可能是“如何将规范模式转换为表达式委托?”

    问题是我不知道他们想要什么表,所以我不知道主键。我用泛型来表示表的类型。

    public interface IRepository<E, C> where C : ObjectContext  // E is an Entity
    {
      void Add(E entity);
      void Del(E entity);
      IList<E> Get(Expression<Func<E, bool>> filterLambda = null,   //Where clause
                  Expression<Func<E, object>> orderbyLambda = null, //OrderBy
                  int? page = null,                                 //Page to get
                  int? pageSize = null,                             //Page Size
                  Expression<Func<E, object>> selectLambda = null); //Populate Fields
      int Count(Expression<Func<E, bool>> filterLambda = null);
      bool SaveChanges();
    }
    

    我用来从数据上下文(数据容器?)是

    this.GetEntity().Where(filterLambda)
                    .OrderBy(orderbyLambda)
                    .Skip(((int)page - 1) * (int)pageSize)
                    .Take((int)pageSize)
                    .Select(selectLambda).ToList();
    

    需要 OrderBy() .Skip() .Take() . 对于所有认为可以这样做的人来说,Linq to SQL是正确的。但是,Linq to实体不支持它:

    The method 'Skip' is only supported for sorted input in LINQ to Entities.
    The method 'OrderBy' must be called before the method 'Skip'.
    
    1 回复  |  直到 14 年前
        1
  •  3
  •   Guffa    14 年前

    您不必在单个语句中构建查询。因为在执行 ToList 最后,您可以使用条件来构建它。例子:

    var query = myDB.Where(p => p.field == "filter");
    
    string sort = "productID, productName";
    
    string[] sortItems = sort.Split(new string[] {", "}, StringSplitOptions.None);
    switch (sortItems[0]) {
      case "productId": query = query.OrderBy(x => x.ProductId); break;
      case "productName": query = query.OrderBy(x => x.ProductName); break;
    }
    for (int i = 1; i < sortItems.Length; i++) {
      switch (sortItems[i]) {
        case "productId": query = query.ThenBy(x => x.ProductId); break;
        case "productName": query = query.ThenBy(x => x.ProductName); break;
      }
    }
    query = query.Skip(10).Take(10);
    

    IEnumerable<T> IOrderedEnumerable<T> ),因此您可能需要更多的变量来存储不同的阶段。)