views:

11515

answers:

7

For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this?

+11  A: 

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.

NotMyself
+47  A: 

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) and SetMaxResult(int i) which indicates the number of rows you wish to get (e.g., your page size).

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

criteria.SetFirstResult(0).SetMaxResult(10);
Jon Limjap
This is pretty much what the Linq (to NH) syntax would look like anyway - Nice.
MotoWilliams
It's important to note that you will need to execute a separate transaction for retrieving the total row count in order to render your pager.
Kevin Pang
This performs a SELECT TOP query in SQL Server. Try it with SetFirstResult(1).SetMaxResult(2);
Chris S
That's previous comment is using NHibernate.Dialect.MsSql2000Dialect not NHibernate.Dialect.MsSql2005Dialect
Chris S
+4  A: 

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 put implementation, but you could use the methods suggested by @Jon. Here's a good discution for you to take a look.

Marcio Aguiar
A: 

Note linq to Nhibernate is in the contrib package and not included in NHibernate 2.0 release

Richard
+5  A: 

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];
zadam
+20  A: 
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

Barbaros Alp
+17  A: 

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.

Jeremy DeVoss
Great stuff, thanks
Igor Brejc
This is great. Futures works exactly like multicriteria without the syntactical complexity of multicriteria.
DavGarcia