如何使用 NHibernate 进行分页?

例如,我想在 ASP.NET 网页中填充一个 gridview 控件,只显示 # 行所需的数据。NHibernate 如何支持这一点?

52456 次浏览

How about using Linq to NHibernate as discussed in this blog post by Ayende?

Code Sample:

(from c in nwnd.Customers select c.CustomerID)
.Skip(10).Take(10).ToList();

And here is a detailed post by the NHibernate team blog on Data Access With NHibernate including implementing paging.

ICriteria has a SetFirstResult(int i) method, which indicates the index of the first item that you wish to get (basically the first data row in your page).

It also has a SetMaxResults(int i) method, which indicates the number of rows you wish to get (i.e., your page size).

For example, this criteria object gets the first 10 results of your data grid:

criteria.SetFirstResult(0).SetMaxResults(10);

I suggest that you create a specific structure to deal with pagination. Something like (I'm a Java programmer, but that should be easy to map):

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()


}

I didn't supply an implementation, but you could use the methods suggested by @Jon. Here's a good discussion for you to take a look.

Most likely in a GridView you will want to show a slice of data plus the total number of rows (rowcount) of the total amount of data that matched your query.

You should use a MultiQuery to send both the Select count(*) query and .SetFirstResult(n).SetMaxResult(m) queries to your database in a single call.

Note the result will be a list that holds 2 lists, one for the data slice and one for the count.

Example:

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

When paging data is there another way to get typed result from MultiCriteria or everyone does the same just like me ?

Thanks

You can also take advantage of the Futures feature in NHibernate to execute the query to get the total record count as well as the actual results in a single query.

Example

 // 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>();

To get the total record count, you do the following:

int iRowCount = rowCount.Value;

A good discussion of what Futures give you is here.

From NHibernate 3 and above, you can use QueryOver<T>:

var pageRecords = nhSession.QueryOver<TEntity>()
.Skip((PageNumber - 1) * PageSize)
.Take(PageSize)
.List();

You may also want to explicitly order your results like this:

var pageRecords = nhSession.QueryOver<TEntity>()
.OrderBy(t => t.AnOrderFieldLikeDate).Desc
.Skip((PageNumber - 1) * PageSize)
.Take(PageSize)
.List();

You don't need to define 2 criterias, you can define one and clone it. To clone nHibernate criteria you can use a simple code:

var criteria = ... (your criteria initializations)...;
var countCrit = (ICriteria)criteria.Clone();