c# - 使用NHibernate的Multi Query功能时遇到 "undefined alias or unknown mapping"异常

标签 c# nhibernate nhibernate-mapping

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

我一直在遵循 here 给出的示例作者:Ayende Rahien,我的代码与它非常相似。但是,每次调用以列表形式返回结果时,都会引发异常,并显示以下消息:

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

您需要提供映射才能使其工作吗?我不认为是这种情况,因为它被返回到通用列表,但如果是这样,您将如何在 Hibernate 的映射文件(即 hbm.xml 文件)中执行此操作?

最佳答案

您和您提供的链接中的 Ayende 正在 HQL 中创建查询使用CreateQuery方法。这种类型的 NH 查询必须针对 NH 实体编写,这意味着您必须有一个正确的映射,即 Sales 实体,然后编写 select count(*) from Sale正如 Ayende 从 Item 中选择的那样。

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

简而言之 - 替换

NHibernateSession.CreateQuery("select ..

NHibernateSession.CreateSQLQuery("select ..

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

关于c# - 使用NHibernate的Multi Query功能时遇到 "undefined alias or unknown mapping"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677930/

相关文章:

NHibernate Fluent 与属性

nhibernate - 是否可以为 Fluent NHibernate Automapping 使用私有(private)字段约定?

c# - 转换为VB后, 'is an event and cannot be called directly.'

nhibernate - 将 NHibernate 实体映射到基于父级的多个表

c# - 如何在 NHibernate QueryOver 查询中选择和使用值对象的集合

asp.net-mvc - 将 ASP.NET MVC NHibernate 应用程序部署到 IIS7 时出错

NHibernate - 将两个相同类型的集合映射到数据库

c# - 调试 DocumentDB 触发器

c# - 使用 http :\\URL 的 WPF 图像 UriSource 和数据绑定(bind)

c# - C# 中的 IComparable