2008-09-10 3 views

답변

107

ICriteria에는 SetFirstResult(int i) 메서드가 있습니다.이 메서드는 얻을 첫 번째 항목의 인덱스 (기본적으로 페이지의 첫 번째 데이터 행)를 나타냅니다.

또한 얻으려는 행 수 (즉, 페이지 크기)를 나타내는 SetMaxResults(int i) 방법이 있습니다. 난 당신이 페이지 매김을 처리하는 특정 구조를 만들 것을 제안

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

이것은 Linq (NH에 대한) 구문이 어쨌든 유사하게 보일 것입니다 - Nice. – MotoWilliams

+13

호출기를 렌더링하려면 총 행 수를 검색하기 위해 별도의 트랜잭션을 실행해야합니다. –

+1

SQL Server에서 SELECT TOP 쿼리를 수행합니다. SetFirstResult (1)로 시도해보십시오 .SetMaxResult (2); –

23

Ayende의 this blog post에서 논의 된 것처럼 Linq를 NHibernate에 사용하는 것은 어떻습니까?

코드 샘플 : 여기

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

그리고 페이징을 구현 포함 Data Access With NHibernate에 NHibernate에 팀 블로그로 상세한 게시물입니다.

+0

자 NHibernate에 참고 LINQ가있는 contrib 패키지에 있고 자 NHibernate에 포함되지 2.0 release – Richard

6

:

예를 들어,이 기준의 목적은 데이터 그리드의 처음 10 개 결과를 가져옵니다. 같은 뭔가 (내가 자바 프로그래머하지만,이 매핑하기 쉬워야한다) :

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에 의해 제안 된 방법을 사용할 수 있습니다. 여기에 good discussion이 있습니다.

11

GridView에서는 대부분 데이터 조각에 쿼리와 일치하는 총 데이터 양 (행 개수)의 합계를 더한 값으로 표시하려고합니다.

단일 호출로 Select count (*) 쿼리와 .SetFirstResult (n) .SetMaxResult (m) 쿼리를 데이터베이스에 보내려면 MultiQuery를 사용해야합니다.

결과는 데이터 슬라이스와 카운트를위한 두 개의 목록을 보유하는 목록입니다.

예 :

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]; 
31
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에서 결과를 입력받을 수있는 또 다른 방법이 또는 모든 사람들이 나처럼 동일합니까? 당신은 또한 선물을 활용할 수

감사

87

은 전체 레코드가 단일 쿼리에서 실제 결과뿐만 아니라 계산 얻을 수있는 쿼리를 실행하는 자 NHibernate에 있습니다. 선물은 당신이 here이다주는 무엇

int iRowCount = rowCount.Value; 

좋은 토론 :

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

예는 총 레코드 수를 얻으려면 다음을 수행합니다.

+1

좋은 물건, 고마워 –

+3

이것은 위대하다. 선물은 여러 가지 정신의 구문 론적 복잡성없이 여러 가지 정신과 똑같이 작동합니다. – DavGarcia

+0

Future에 대한 게시물을 읽은 후 모든 데이터베이스 쿼리에 대해 Future를 사용해야하는지 궁금해졌습니다 ... 단점은 무엇입니까? :) – hakksor

39

NHibernate에 3에서는 QueryOver이

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

당신은 명시 적으로이 같은 결과를 주문 할 수 있습니다 사용할 수 있습니다

var pageRecords = nhSession.QueryOver<TEntity>() 
      .OrderBy(t => t.AnOrderFieldLikeDate).Desc 
      .Skip(PageNumber * PageSize) 
      .Take(PageSize) 
      .List(); 
관련 문제