Nhibernate Icreteria 分页查询

1、创建查询条件,条件为一个ICreterion的列表

///
        /// 创建Criteria(不含order,因为获取总数的时候,为了性能考虑,不加order)
        ///
        /// 类型
        /// ICriterion列表
        ///
        public ICriteria CreateCriteria(Type t, List list)
        {
            ICriteria criteria = Session.CreateCriteria(t);

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

return criteria;
        }

2、分页查询

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

int startNum = pageInfo.CurrentPage * pageInfo.PageSize;

//创建一个同样的ICriteria对象,不然执行总数查询之后,ICriteria的条件依然还是总数查询,下边的结果查询会出错。

ICriteria pageCriteria = CriteriaTransformer.Clone(c);

//执行结果查询,Projections对象会投影到一个新的查询,包含AVG、sum、count等等
           pageInfo.RowCount = int.Parse(pageCriteria.SetProjection(Projections.RowCount()).UniqueResult().ToString());

//执行完总数查询之后,就给之前的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; }
        }

}

上一篇:POJ 1176 Party Lamps (DFS)


下一篇:border 三角形 有边框的 东西南北的 气泡三角形