Using MvcPager with Fluent NHibernate

Feb 17, 2011 at 7:41 PM

Hello,

Is it possible to use the MvcPager with Fluent NHibernate?

 

I can get it to work using something like this:

        public virtual PagedList<T> GetPagedData(int? startIndex, int count) {
            return session.CreateCriteria(typeof(T).List<T>().AsQueryable().ToPagedList(startIndex ?? 1, count);
        }

However, doing this is going to query the entire table each time.

I like the ease and look of the MvcPager, however I can't have it query a large table everytime I flip through a page.  Please let me know if there is a way to do this.

Thanks!

Feb 17, 2011 at 9:18 PM

I think I figured this out, what I needed to do is write my own implemenation of ToPagedList().

 

My new method looks like this:

public virtual PagedList<T> GetPagedData(int startIndex, int count) {
            
      var rowCount = session.CreateCriteria(typeof(T)).SetProjection(Projections.RowCount()).FutureValue<Int32>().Value;

      var pageOfItems = session.CreateCriteria(typeof(T)).SetFirstResult(startIndex).SetMaxResults(count).List<T>();
      return new PagedList<T>(pageOfItems, startIndex, count, rowCount);
}
Hope this helps out someone...
Mar 13, 2011 at 6:44 AM

@Brosto

    u can download the MvcPager Source,and edit "PageLinqExtensions.cs" , add two methods....

    hope this can help u..

  

public static PagedList<T> ToPagedList<T>
            (
                this IQueryable<T> allItems,
                int pageIndex,
                int pageSize,
                int totalCount
            )
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var totalItemCount = totalCount;
            return new PagedList<T>(allItems, pageIndex, pageSize, totalItemCount);
        }

        public static PagedList<T> ToPagedList<T>
            (
                this IEnumerable<T> allItems,
                int pageIndex,
                int pageSize,
                int totalCount
            )
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var totalItemCount = totalCount;
            return new PagedList<T>(allItems, pageIndex, pageSize, totalItemCount);
        }

 

Dec 13, 2011 at 2:48 AM
Edited Dec 13, 2011 at 2:59 AM

If you are using IQueryOver (in NHibernate), below may help. Just add it to the PageLinqExtensions class. Note the use of futures to reduce the number of hits to the database.

        public static PagedList<T> GetPagedData<T>(this IQueryOver<T, T> allItems, int pageIndex, int pageSize)
        {
            var rowCount = allItems.ToRowCountQuery().FutureValue<int>();

            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var pageOfItems = allItems.Skip(itemIndex).Take(pageSize).Future();

            return new PagedList<T>(pageOfItems, pageIndex, pageSize, rowCount.Value);
        }