Nhibernate使用HQL返回自定义类型
时间:2010-08-25 来源:.net's
摘要:使用HQL返回自定义类型的结果集。
前提:已经定义好Customer类及其Nhibernate映射文件xml。
表结构及数据
自定义类
Mapping文件
条件查询(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
相关阅读 更多 +