0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.