简体   繁体   中英

NHibernate query count

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..

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM