CreateSqlQuery不会在NHibernate中检索标量值

时间:2010-11-12 23:32:17

标签: nhibernate

为什么codigoUnificacion变量始终为空?

public int? GetCodigoUnificacionFamiliar(IList<Pariente> parientes)
        {
            List<string> cedulas = new List<string>();

            parientes.ToList().ForEach(p => cedulas.Add(p.Cedula));

            int? codigoUnificacion = Session
                .CreateSQLQuery(@"SELECT DISTINCT
                                            sa_bec_mtc_doc as Codigo
                                    FROM    sa_bec_matricula
                                            INNER JOIN sa_matricula ON sa_bec_matricula.sa_mtc_num = sa_matricula.sa_mtc_num
                                            INNER JOIN sa_alumno ON sa_matricula.sa_alu_cod = sa_alumno.sa_alu_cod
                                            INNER JOIN sa_periodo ON sa_matricula.sa_per_cod = sa_periodo.sa_per_cod
                                            INNER JOIN sa_tpo_beca ON sa_bec_matricula.sa_tpo_bec_cod = sa_tpo_beca.sa_tpo_bec_cod
                                    WHERE   sa_alu_ced IN (:cedulas)
                                            AND sa_per_abi = 1
                                            AND sa_tpo_bec_gpr = 2")
                .SetParameterList("cedulas", cedulas)
                .UniqueResult() as int?;

            return codigoUnificacion;
        }

2 个答案:

答案 0 :(得分:9)

执行在NHibernate中返回标量值的查询

这会有效!

var max = session.CreateSQLQuery(query).UniqueResult();
decimal s = max != null ? Decimal.Parse(max.ToString()) : -1;

这将返回null !!!

decimal? s = session.CreateSQLQuery(query).UniqueResult() as decimal?;

这不会编译

因为只接受引用或可空类型

decimal s = session.CreateSQLQuery(query).UniqueResult() as decimal;

<强> TypeConversionException

NHibernate抛出异常

decimal s = (decimal)session.CreateSQLQuery(query).UniqueResult();

答案 1 :(得分:1)

您可以定义您期望的类型,而不是使用var。

示例

int max = session.CreateSQLQuery(query).UniqueResult<int>();

这样你就不必在事后尝试施放演员。