【问题标题】:Nhibernate - Create SQLQuery - IndexOutOfRangeExceptionNhibernate - 创建 SQLQuery - IndexOutOfRangeException
【发布时间】:2010-02-08 10:10:43
【问题描述】:

我们有一个名为 Customer 的表,它有三个子类/表,即。 Cust1、Cust2、Cust3,由hbm使用joined-sub-class链接。

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

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

但是,为了优化我们的查询,我们不得不使用 CreateSQlQuery 方法。

在谷歌上,我们发现获取类及其子类的正确方法是 有一个选择查询,例如

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();

当 Nhibernate 在内部生成查询时,需要更改大小写和 alais 以区分 4 个表之间的 CUstId 列,否则将引发 clazz 错误..

在运行查询时,我们得到 Nhibernate 异常

“IndexOutOfRangeException - 持续时间”

Cust1(子类)表有一个名为 Duration 的列。我将表列重命名为 Duration_BE 以检查列名是否为问题,, 然后它抛出了错误

“IndexOutOfRangeException - Duration-BE”

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

谁能帮帮我。

【问题讨论】:

标签: c# nhibernate


【解决方案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)"
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多