NHibernate:存储过程和组件

时间:2011-08-24 02:52:37

标签: nhibernate stored-procedures nhibernate-mapping

我将一个存储过程称为NamedQuery,它正在运行 精细。 当我尝试加载组件时,问题就开始了。 存储过程返回一个像这样的记录集

[IDEmployee,EmployeeName,City,Country]

IDEmployee和EmployeeName属于映射实体,City和Country属于组件

这是映射:

<class name="Employee" table="employees"> 
    <id name="IDEmployee"> 
      <column name="idemployee" /> 
      <generator class="native" /> 
    </id> 
    <property name="EmployeeName "> 
      <column name="employeename" /> 
    </property> 
    <component name="Address" class="Address"> 
      <property name="City"> 
        <column name="city" /> 
      </property> 
      <property name="Country"> 
        <column name="country" /> 
      </property> 
    </component> 
  </class> 

这是我用来调用存储过程的代码:

  <sql-query name="GetEmployeesByCompany"> 
    <return class="Employee"> 
      <return-property column="idemployee" name="IDEmployee" /> 
      <return-property column="employeename" name="EmployeeName" /> 
      <return-property column="city" name="City" /> 
      <return-property column="country" name="Country" /> 
    </return> 
    EXEC GetEmployeeByCompany:idcompany 
  </sql-query> 

这里我用来调用存储的代码:

 var result = 
    session<ISession>().GetNamedQuery("GetEmployeesByCompany") 
                .SetInt32("idcompany", companyId) 
                .List<Employee>().ToList(); 

这是我运行应用时遇到的错误

System.IndexOutOfRangeException: t1_282_0_ 
   at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name) 
   at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name) 
in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Type\NullableType.cs:line 236 
   at NHibernate.Persister.Entity.AbstractEntityPersister.Hydrate(IDataReader rs, Object id, Object obj, ILoadable rootLoadable, String[][] suffixedPropertyColumns, Boolean allProperties, ISessionImplementor session)
in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs:line 2508
   at NHibernate.Loader.Loader.LoadFromResultSet(IDataReader rs, Int32 i, Object obj, String instanceClass, EntityKey key, String rowIdAlias, LockMode lockMode, ILoadable rootPersister, ISessionImplementor session) 
in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 991 

如果我从地图中删除组件一切正常。 我还尝试使用带有嵌套返回列的return-property但没有成功。

任何提示?谢谢!

1 个答案:

答案 0 :(得分:5)

我最近不得不面对这个问题,这就是我出来的方式。

<sql-query name="GetEmployeesByCompany">
  <return class="Employee">
    <return-property column="idemployee" name="IDEmployee" />
    <return-property column="employeename" name="EmployeeName" /> 
    <return-property name="Address">  <!-- name of the component -->
      <return-column name="city" />  <!-- name of the resultset field -->
      <return-column name="country" />  <!-- name of the resultset field -->
    </return-property>
</return> 
EXEC GetEmployeeByCompany:idcompany 

您对return属性中的字段使用的顺序非常重要,它必须与结果集中的字段匹配。根本没有文档,我希望这可以帮到你!