This might be common knowledge for those that use NHibernate - but it's new to me, since I am not an NHibernate power-user, yet.
Given this object model:
public class Invoice
{
private int _id = 0;
private string _invoiceNumber = string.Empty;
private DateTime _invoiceDueDate = DateTime.MinValue;
private ICollection<InvoiceDetail> _invoiceDetails = new HashedSet<InvoiceDetail>();
public int Id
get { return _id; }
}
public string InvoiceNumber
get { return _invoiceNumber; }
set { _invoiceNumber = value; }
public DateTime InvoiceDueDate
get { return _invoiceDueDate; }
set { _invoiceDueDate = value; }
public ICollection<InvoiceDetail> InvoiceDetails
get { return _invoiceDetails; }
public InvoiceDetail CreateDetail()
InvoiceDetail detail = new InvoiceDetail();
InvoiceDetails.Add(detail);
return detail;
public class InvoiceDetail
internal InvoiceDetail() { }
private string _productName = string.Empty;
private decimal _productCost = 0;
private int _productQuantity = 0;
public string ProductName
get { return _productName; }
set { _productName = value; }
public decimal ProductCost
get { return _productCost; }
set { _productCost = value; }
public int ProductQuantity
get { return _productQuantity; }
set { _productQuantity = value; }
We can load any invoice that has an Invoice Detail with a specific Product Name, using this NHibernate code:
invoices = Session.CreateCriteria(typeof(Invoice))
.CreateCriteria("InvoiceDetails")
.Add(Expression.Eq("ProductName", productName))
.List<Invoice>();
Additionally, we can add paging to the result set, by including the SetFirstResult and SetMaxResult calls in the Criteria.
.SetFirstResult(pageSize * pageNumber)
.SetMaxResults(pageSize - 1)
Notice the use of pageSize and PageNumber to set the First Result value - this creates an index-by-zero page number that we want to view. For example, if our page size is 10 and we are on page zero, then the FirstResult is going to be 0 and the last result will be 9. 0 through 9 = 10 results. If we are on page 3, then the FirstResult is 30 and the MaxResult is 39...
Works pretty well... now, let's just hope that the actual underlying database implementation of this can take advantage of each DBMS' optimizations for doing this.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.