2010-02-08 58 views
2

我们有一个名为Customer的表,它有三个子类/表,即, Cust1,Cust2和Cust3通过hbm使用联合子类链接。Nhibernate - 创建SQLQuery - IndexOutOfRangeException

所有的4个表都以CustomerId作为主键。客户表中的记录将在Cust1或Cust2或Cust3表中有一条记录。

使用标准的Nhibernate List()获取列表正确地获取类及其子类。

但是,为了最优化我们的查询,我们必须使用CreateSQlQuery方法。

在goolging,我们发现,正确的方法来获取类及其子类是 有诸如

var sqlQuery = Session.CreateSqlQuery(
select C.*, 
case if C1.CustId is not null then 1 
else if C2.CustId is not null then 2 
.... 
from Customer C 
left join Cust1 C1 on C1.CustId = C1.CustId 
left join Cust2 C2 on C2.CustId 

where C.CustID in (x,y,z,blah,blah).). 

sqlQuery.AdddEntity("C",typeof(Customer)); 

sqlQuery.List(); 

需要的情况和alais变化区分之间的CUSTID列的选择查询当NHibernate的genereates查询内部,否则有clazz中的错误将会被抛出4个表..

运行查询,我们得到,NHibernate的异常如

“IndexOutOfRangeException - 持续时间”

Cust1(子类)表中有一个名为列持续时间。我改名为表列Duration_BE检查,如果列名是一个问题, 那么它扔了错误

“IndexOutOfRangeException - 持续时间-BE”

工作的这种模式参考是.. http://www.methodicmadness.com/2009/01/nhibernate-what-is-heck-clazz.html

任何人都可以帮助我。

+0

这个问题非常具体,应该发布到NHibernate用户组:http://groups.google.com/group/nhusers – zvolkov 2010-02-09 17:33:25

回答

1

确保您选择了所有表格中的所有字段。

例如

var sqlQuery = Session.CreateSqlQuery(@" 
    select 
    C.*, 
    C1.*, 
    C2.*, -- You need all of the fields from the joined tables 
    case 
     if C1.CustId is not null then 1 
     else if C2.CustId is not null then 2 
    end as clazz_ 
    from 
    Customer C 
    left join Cust1 C1 on C.CustId = C1.CustId 
    left join Cust2 C2 on C.CustId = C2.CustId 
    where 
    C.CustID in (x,y,z)" 
);