tags:

views:

82

answers:

1

Hi, I am new to NHibernate and I want to have a count of rows from database. Below is my code,

SearchTemplate template = new SearchTemplate();
            template.Criteria = DetachedCriteria.For(typeof(hotel));
            template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
            template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
    int count = template.Criteria.SetProjection(Projections.Count("ID"));

It gives me an error when I try to compile app that says "Cannot implicitly convert type 'NHibernate.Criterion.DetachedCriteria' to 'int'"

I want to have a count of rows of the table hotel..

+1  A: 

You want to use GetExecutableCriteria:

SearchTemplate template = new SearchTemplate();
        template.Criteria = DetachedCriteria.For(typeof(hotel));
        template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
        template.Criteria.Add(Restrictions.Eq("Canceled", "False"));

var count = DoCount(template.Criteria, session /* your session */);

public long DoCount(DetachedCriteria criteria, ISession session)
{
     return Convert.ToInt64(criteria.GetExecutableCriteria(session)
                   .SetProjection(Projections.RowCountInt64())
                   .UniqueResult());
}

On a side note, you should take a look at using NHibernate.Linq:

var result = (from h in Session.Linq<Hotel>()
             where h.CheckOutDate <= SelDate
             where h.Canceled != true
             select h).Count();

More information here.

Rafael Belliard
How would I use it in my situation. How would I change the above code that I have posted so that it uses the function that you have provided?
developer
@developer I edited to reflect your usage.
Rafael Belliard