NHibernate实现查询分页

NHibernate是一个O/RM框架,在增删改查等操作时我们可以直接在程序中编写语句实现不用再去写SQL语句。查询所有记录,在NHibernate中是很容易实现的,不过分页的实现就不能像在数据库中直接写SQL语句那样方便了。

实现分页时主要利用了Skip和Take方法。具体代码如下。

public IList<T> LoadByPage(int pageIndex, int pageSize,out int totalCount)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                totalCount = session.QueryOver<T>().RowCount();	//总条数
                return session.QueryOver<T>().Skip((pageIndex - 1) * pageSize).Take(pageSize).List();
            }
        }


运行时生成的SQL语句与结果,如下。

测试名称:	LoadByPageTest
测试结果:	已通过
结果 的标准输出:	
NHibernate: SELECT count(*) as y0_ FROM T_Product this_	--总行数

--第一页,由此可见看到如果是第一页,NHibernate只是简单的利用TOP()函数选出页面需要的条数的记录
NHibernate: SELECT TOP (@p0) this_.ID as ID1_1_0_, this_.Code as Code2_1_0_, this_.Name as Name3_1_0_, this_.QuantityPerUnit as Quanti4_1_0_, this_.Unit as Unit5_1_0_, this_.SellPrice as SellPr6_1_0_, this_.BuyPrice as BuyPri7_1_0_, this_.Remark as Remark8_1_0_, this_.BusinessID as Busine9_1_0_ FROM T_Product this_;@p0 = 2 [Type: Int32 (0:0:0)]

--结果
电脑
手机

NHibernate: SELECT count(*) as y0_ FROM T_Product this_	--总行数

--第二页,从第二页开始NHibernate利用了ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP)函数来实现分页,如果是在低版本中sql2005及更低版本中应该是另外一种方式实现了。
NHibernate: SELECT TOP (@p0) ID1_1_0_, Code2_1_0_, Name3_1_0_, Quanti4_1_0_, Unit5_1_0_, SellPr6_1_0_, BuyPri7_1_0_, Remark8_1_0_, Busine9_1_0_ FROM (SELECT this_.ID as ID1_1_0_, this_.Code as Code2_1_0_, this_.Name as Name3_1_0_, this_.QuantityPerUnit as Quanti4_1_0_, this_.Unit as Unit5_1_0_, this_.SellPrice as SellPr6_1_0_, this_.BuyPrice as BuyPri7_1_0_, this_.Remark as Remark8_1_0_, this_.BusinessID as Busine9_1_0_, ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) as __hibernate_sort_row FROM T_Product this_) as query WHERE query.__hibernate_sort_row > @p1 ORDER BY query.__hibernate_sort_row;@p0 = 2 [Type: Int32 (0:0:0)], @p1 = 2 [Type: Int32 (0:0:0)]

--结果
笔记本电脑
平板电脑



调用。

public List<ProductVM> GetListByPage(int pageIndex,int pageSize)
        {
            int totalCount;	//总条数
            var productIList = productDao.LoadByPage(pageIndex, pageSize,out totalCount);
            List<ProductVM> productListByPage = (from p in productIList
                                                 select new ProductVM
                                                 {
                                                     ID = p.ID,
                                                     Code = p.Code,
                                                     Name = p.Name,
                                                 }).ToList();
            return productListByPage;
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仰望星空的代码

创作不易,您的支持是我的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值