开发者

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", "开发者_如何学PythonFalse"));
    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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜