NHibernate命名查询不返回所有字段

时间:2015-08-04 20:56:43

标签: c# ms-access nhibernate group-by named-query

我在Forecast.hbm.xml中定义了以下命名查询:

SELECT 
    c.ForecastedYear,
    s.Description,
    Sum(c.NumTrees) AS NumTrees
FROM 
    EcoForecasts AS f INNER JOIN 
    (EcoForecastCohorts AS c INNER JOIN EcoStrata AS s ON s.StrataKey = c.StratumKey) 
    ON f.ForecastKey = c.ForecastKey
WHERE 
    f.ForecastKey = :guid
GROUP BY 
    c.ForecastedYear,
    c.StratumKey,
    s.Description
ORDER BY 
    s.Description,
    c.ForecastedYear;

我在C#文件中调用NumTreesByStrataReport.cs中的查询,如下所示:

IList<Result> results = _input.GetNamedQuery("NumTreesByStrata")
                              .SetGuid("guid", _iSess.ForecastKey.Value)
                              .List<object[]>()
                              .Select(result => new Result {
                                  Year     = Convert.ToInt16(result[0]),
                                  Strata   = Convert.ToString(result[1]),
                                  NumTrees = Convert.ToInt64(result[2])
                              })
                              .ToList();

return results;

但是,此代码抛出IndexOutOfRangeException,因为.List<object[]>()部分返回的对象数组列表只包含3个元素。未返回s.Description字段。

如果我在数据库引擎(Microsoft Access)中运行SQL查询,则返回所有3列。为什么NHibernate无法执行数据库可以执行的操作并返回所有选定的字段?

2 个答案:

答案 0 :(得分:1)

我建议将结果用于bean变换器,代码会更清晰。

return _session.GetNamedQuery("NumTreesByStrata")
    .SetGuid("guid", forecastKeyValue)
    .SetResultTransformer(Transformers.AliasToBean(typeof(Result)))
    .List<Result>();

答案 1 :(得分:0)

谢谢大家的帮助。事实证明问题实际上是我的映射文件:

    <sql-query name="NumTreesByStrata">
        <return-scalar column="ForecastedYear" type="Int16"/>
        <return-scalar column="NumTrees" type="Int64"/>
        <![CDATA[
          SELECT c.ForecastedYear,
          ...
        ]]>
    </sql-query>

我添加了缺少的<return-scalar column="Description" type="string"/>元素以使其正常工作。

  

我建议将结果用于bean变换器,代码会更清晰。

感谢Alexey的建议,我不知道你能做到这一点!