码迷,mamicode.com
首页 > Web开发 > 详细

Nhibernate Icreteria 分页查询

时间:2015-02-06 16:23:43      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

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; }
        }

            
    }

Nhibernate Icreteria 分页查询

标签:

原文地址:http://www.cnblogs.com/elim/p/4277310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!