如何使用NHibernate进行分页?
时间:2020-03-05 18:50:54 来源:igfitidea点击:
例如,我想只用显示行数所需的数据填充ASP.NET网页中的gridview控件。 NHibernate如何支持这一点?
解决方案
回答
如Ayende在此博客文章中所讨论的,如何使用Linq进行NHibernate?
代码样例:
(from c in nwnd.Customers select c.CustomerID) .Skip(10).Take(10).ToList();
这是NHibernate团队博客上有关使用NHibernate进行数据访问的详细文章,包括实现分页。
回答
ICriteria具有SetFirstResult(int i)方法,该方法指示我们希望获取的第一项的索引(基本上是页面中的第一数据行)。
它还有一个SetMaxResults(int i)方法,该方法指示我们希望获取的行数(即页面大小)。
例如,此条件对象获取数据网格的前10个结果:
criteria.SetFirstResult(0).SetMaxResults(10);
回答
我建议我们创建一个特定的结构来处理分页。诸如此类(我是一名Java程序员,但是应该很容易映射):
public class Page { private List results; private int pageSize; private int page; public Page(Query query, int page, int pageSize) { this.page = page; this.pageSize = pageSize; results = query.setFirstResult(page * pageSize) .setMaxResults(pageSize+1) .list(); } public List getNextPage() public List getPreviousPage() public int getPageCount() public int getCurrentPage() public void setPageSize() }
我没有提供实现,但是我们可以使用@Jon建议的方法。这是一个很好的讨论,供我们查看。
回答
最有可能在GridView中显示一片数据,再加上与查询匹配的数据总量的总行数(行数)。
我们应该使用MultiQuery在一次调用中将Select count(*)查询和.SetFirstResult(n).SetMaxResult(m)查询都发送到数据库。
请注意,结果将是一个包含2个列表的列表,一个列表用于数据切片,一个列表用于计数。
例子:
IMultiQuery multiQuery = s.CreateMultiQuery() .Add(s.CreateQuery("from Item i where i.Id > ?") .SetInt32(0, 50).SetFirstResult(10)) .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?") .SetInt32(0, 50)); IList results = multiQuery.List(); IList items = (IList)results[0]; long count = (long)((IList)results[1])[0];
回答
public IList<Customer> GetPagedData(int page, int pageSize, out long count) { try { var all = new List<Customer>(); ISession s = NHibernateHttpModule.CurrentSession; IList results = s.CreateMultiCriteria() .Add(s.CreateCriteria(typeof(Customer)).SetFirstResult(page * pageSize).SetMaxResults(pageSize)) .Add(s.CreateCriteria(typeof(Customer)).SetProjection(Projections.RowCountInt64())) .List(); foreach (var o in (IList)results[0]) all.Add((Customer)o); count = (long)((IList)results[1])[0]; return all; } catch (Exception ex) { throw new Exception("GetPagedData Customer da hata", ex); } }
当分页数据时,还有另一种方法可以从MultiCriteria获取类型化的结果,或者每个人都像我一样吗?
谢谢
回答
我们还可以利用NHibernate中的Futures功能来执行查询,以获取单个记录中的总记录数以及实际结果。
例子
// Get the total row count in the database. var rowCount = this.Session.CreateCriteria(typeof(EventLogEntry)) .Add(Expression.Between("Timestamp", startDate, endDate)) .SetProjection(Projections.RowCount()).FutureValue<Int32>(); // Get the actual log entries, respecting the paging. var results = this.Session.CreateCriteria(typeof(EventLogEntry)) .Add(Expression.Between("Timestamp", startDate, endDate)) .SetFirstResult(pageIndex * pageSize) .SetMaxResults(pageSize) .Future<EventLogEntry>();
要获取总记录数,请执行以下操作:
int iRowCount = rowCount.Value;
这里对期货给我们带来了很好的讨论。