NHibernate查询计数

时间:2010-09-24 21:12:49

标签: nhibernate

我是NHibernate的新手,我希望从数据库中获取行数。以下是我的代码,

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"));

当我尝试编译应用程序时,它给我一个错误 “无法将类型'NHibernate.Criterion.DetachedCriteria'隐式转换为'int'”

我想要表酒店的行数。

1 个答案:

答案 0 :(得分:2)

您想使用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());
}

在旁注中,您应该看看使用NHibernate.Linq

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

更多信息here