Nhibernate Icreteria 分頁查詢

一、建立查詢條件,條件爲一個ICreterion的列表性能

        ///
        /// 建立Criteria(不含order,由於獲取總數的時候,爲了性能考慮,不加order)
        ///
        /// 類型
        /// ICriterion列表
        ///
        public ICriteria CreateCriteria(Type t, List list)
        {
            ICriteria criteria = Session.CreateCriteria(t);this

            if (list != null && list.Count > 0)
            {
                foreach (ICriterion c in list)
                {
                    criteria.Add(c);
                }
            }orm

            return criteria;
        }對象

二、分頁查詢排序

        ///
        ///獲取排序的pageInfo
        ///
        /// 類型
        /// ICriterion列表
        /// 升序?true:false
        /// 排序字段
        ///
        public PageInfo getOrderdPagedListByCriteria(PageInfo pageInfo,Type t, List list, bool isAsc, string orderBy)
        {
           ICriteria c= CreateCriteria(t, list);//拼接查詢條件get

           int startNum = pageInfo.CurrentPage * pageInfo.PageSize;string

//建立一個一樣的ICriteria對象,否則執行總數查詢以後,ICriteria的條件依然仍是總數查詢,下邊的結果查詢會出錯。it

           ICriteria pageCriteria = CriteriaTransformer.Clone(c);io

//執行結果查詢,Projections對象會投影到一個新的查詢,包含AVG、sum、count等等
           pageInfo.RowCount = int.Parse(pageCriteria.SetProjection(Projections.RowCount()).UniqueResult().ToString());form

 

//執行完總數查詢以後,就給以前的ICriteria對象建立排序規則

           if (isAsc)
               c.AddOrder(new Order(orderBy, true));
           else
               c.AddOrder(new Order(orderBy, false));

//建立完排序規則以後,執行數據查詢
           pageInfo.Results = c.SetFirstResult(startNum).SetMaxResults(pageInfo.PageSize).List().ToList();

           return pageInfo;
        }

 

注:PageInfo是一個分頁類

 ///
        /// 結果
        ///
        public List Results { get; set; }

        ///
        /// 當前頁碼
        ///
        public int CurrentPage { get; set; }

        ///
        /// 頁總數(一共有多少頁)
        ///
        public int PageCount
        {
            get
            {
                if (RowCount == 0)
                {
                    return 1;
                }
                else
                {
                    return (int)Math.Ceiling(RowCount / (double)PageSize);
                }
            }
            private set
            {
                this.PageCount = value;
            }
        }

        ///
        /// 總記錄數
        ///
        public int RowCount { get; set; }

        ///
        /// 每頁記錄數
        ///
        private int pagesize;
        public int PageSize
        {
            get { return pagesize; }
            set { pagesize = value; }
        }

                }

相關文章
相關標籤/搜索