使用 NHibernate 的多查询功能时遇到 "undefined alias or unknown mapping" 异常

Encountering an "undefined alias or unknown mapping" exception when using NHibernate's Multi Query feature

我正在尝试使用 NHibernate 版本 v2.0.50727 为典型的分页和计数功能实现 NHibernate 的多查询功能。

我一直在关注 Ayende Rahien here 给出的示例,我的代码与它非常相似。但是,每次它调用 return 结果作为列表时,都会抛出一个异常,消息如下:

"undefined alias or unknown mapping: Shop [from Shop.dbo.Sales s where s.Customer = :customer_id and s.date between :start_date and :end_date order by s.date desc]"

这是代码中出现问题的步骤:

        IList queryResults = NHibernateSession.CreateMultiQuery()
            .Add(dataQuery)
            .Add(countQuery)
            .List();

这是代码的其余部分:

        private IList < SalesDetails > GetSalesByCustomer(Customer customer, DateTime start, DateTime end, int pageIndex, int pageSize, out int TotalCount)
     {
        IQuery dataQuery = NHibernateSession.CreateQuery("from Shop.dbo.Sales s where s.Customer = :customer_id and s.date between :start_date and :end_date order by s.date desc");
        dataQuery.SetInt32("customer_id", customer.ID);
        dataQuery.SetParameter("start_date", start);
        dataQuery.SetParameter("end_date", end);
        dataQuery.SetFirstResult(pageIndex);
        dataQuery.SetMaxResults(pageSize);

        IQuery countQuery = NHibernateSession.CreateQuery("select count(*) from Shop.dbo.Sales s where s.Customer = :customer_id and s.date between :start_date and :end_date");
        countQuery.SetInt32("customer_id", customer.ID);
        countQuery.SetParameter("start_date", start);
        countQuery.SetParameter("end_date", end);

        IList queryResults = NHibernateSession.CreateMultiQuery()
            .Add(dataQuery)
            .Add(countQuery)
            .List();

        IList < SalesDetails > results = (IList < SalesDetails > ) queryResults[0];
        TotalCount = (int)((IList) queryResults[1])[0];
        return results;
    }

你需要提供一个映射才能工作吗?我不认为是这种情况,因为它被 return 编辑到通用列表,但如果是这样,您甚至如何在 Hibernate 的映射文件中执行此操作,即 hbm.xml , 文件?

您和您提供的 link 中的 Ayende 正在使用 CreateQuery 方法在 HQL 中创建查询。这种类型的 NH 查询必须针对 NH 实体编写,这意味着您必须具有适当的映射,即 Sales 实体,然后按照 Ayende 从 Item.[= 中选择的方式编写 select count(*) from Sale 20=]

如果你想使用SQL而不是CreateQuery,你应该使用CreateSQLQuery方法。您可以复习 the manual 的第 14-17 章。可惜您使用的是旧版本,否则我建议您将 linq 作为您选择的查询方法。

简而言之 - 替换

NHibernateSession.CreateQuery("select ..

NHibernateSession.CreateSQLQuery("select ..

或者使用映射的实体名称而不是基于 SQL table 的标识符编写正确的 HQL 查询。