摘要:使用HQL返回自定义类型的结果集。

前提:已经定义好Customer类及其Nhibernate映射文件xml。

表结构及数据

Nhibernate使用HQL返回自定义类型

自定义类

Nhibernate使用HQL返回自定义类型

Mapping文件

Nhibernate使用HQL返回自定义类型

条件查询(Criteria Query)

public IList<CustomerFirstnameCounter> GetCustomerFirstnameCounts()
        {
            ISession session = GetSession();
            return session.CreateQuery(@"select new CustomerFirstnameCounter(c.Firstname,count(c.Firstname)) 
            from Customer c group by c.Firstname")
                .List<CustomerFirstnameCounter>();
        }

输出SQL

NHibernate: select customer0_.Firstname as col_0_0_, count(customer0_.Firstname) as col_1_0_ from Customer customer0_ group by customer0_.Firstname

说明

CustomerFirstnameCounter中的Count属性必须定义为long类型,如果定义为int类型,则会报如下错误:

Test method DataAccessLayer.Test.NhibernateDataProviderTest.GetCustomerFirstnameCountsTest threw exception: 
NHibernate.QueryException: Unable to locate appropriate constructor on class [DataTransfer.CustomerFirstnameCounter, DataTransfer] [select new CustomerFirstnameCounter(c.Firstname,count(c.Firstname)) 
            from DataTransfer.Customer c group by c.Firstname] ---> NHibernate.InstantiationException: no constructor compatible with (System.String, System.Int64) found in class: DataTransfer.CustomerFirstnameCounter

相关文章:

  • 2021-12-19
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-31
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-21
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2022-12-23
  • 2021-05-22
相关资源
相似解决方案