문제

예를 들어, 표시된 행 수에 필요한 데이터만 사용하여 ASP.NET 웹 페이지의 Gridview 컨트롤을 채우고 싶습니다.NHibernate는 이것을 어떻게 지원할 수 있나요?

도움이 되었습니까?

해결책

ICriteria 가지고있다 SetFirstResult(int i) 가져오려는 첫 번째 항목(기본적으로 페이지의 첫 번째 데이터 행)의 인덱스를 나타내는 메서드입니다.

그것은 또한 SetMaxResults(int i) 가져오려는 행 수(예: 페이지 크기)를 나타내는 메서드입니다.

예를 들어 이 기준 개체는 데이터 그리드의 처음 10개 결과를 가져옵니다.

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

다른 팁

또한 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;

Futures가 제공하는 것에 대한 좋은 토론은 다음과 같습니다. 여기.

NHibernate 3 이상에서는 다음을 사용할 수 있습니다. QueryOver<T>:

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

다음과 같이 결과를 명시적으로 정렬할 수도 있습니다.

var pageRecords = nhSession.QueryOver<TEntity>()
            .OrderBy(t => t.AnOrderFieldLikeDate).Desc
            .Skip((PageNumber - 1) * PageSize)
            .Take(PageSize)
            .List();
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에서 입력된 결과를 얻는 다른 방법이 있습니까? 아니면 모두가 저처럼 똑같이 합니까?

감사해요

에서 설명한 대로 Linq를 NHibernate에 사용하는 것은 어떻습니까? 이 블로그 게시물 아옌데로?

코드 샘플:

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

그리고 여기에 NHibernate 팀 블로그의 자세한 게시물이 있습니다. NHibernate를 통한 데이터 액세스 페이징 구현을 포함합니다.

대부분의 경우 GridView에서는 쿼리와 일치하는 총 데이터 양의 데이터 조각과 총 행 수(rowcount)를 표시하려고 할 것입니다.

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

결과는 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];

페이지 매김을 처리하기 위해 특정 구조를 만드는 것이 좋습니다.다음과 같습니다(저는 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()

}

나는 구현을 제공하지 않았지만 다음에서 제안한 방법을 사용할 수 있습니다. @존.여기 좋은 토론 당신이 살펴 볼 수 있도록.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top