如何为NHibernate命名查询中的参数提供值

时间:2010-02-22 13:55:35

标签: nhibernate parameters named

我收到以下错误:“消息:没有给出一个或多个必需参数的值。”当我尝试从MBUnit测试代码时。

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="myApplication.Core" namespace="studentTrak">


  <class name="UniversityCourse" table="UniversityCourse" lazy="true">

    <id name="Id" column="ID" type="int">
      <generator class="native" />
    </id>

    <property name="Name" column="Name" type="string"  not-null="true"/>
    <property name="Description" column="Description" type="string" />


    <many-to-one name="BestStudent" class="Student"/>
    <loader query-ref="GetBestStudent"/>

  </class>
  <sql-query name="GetBestStudent" callable="true">
    <return class="Student">
    </return>
    SELECT *  FROM BestStudents WHERE CourseId = ?
  </sql-query>
</hibernate-mapping>

该实体的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace studentTrak
{
    public class UniversityCourse 
    {

        public virtual int Id { get; set; }
        public virtual String Description { get; set; }
        public virtual String Name {get;set;}


        public virtual Student BestStudent
        {
            get;
            set;
        }
    }
}

如何提供命名查询所需的值?

1 个答案:

答案 0 :(得分:2)

错误说明了一切: 您检索命名查询,并希望执行它。 虽然,正如您在代码中看到的那样,命名查询在其where子句中有一个参数。 您必须为命名查询提供其参数的值,否则无法执行。

这样的事情:

IQuery q = session.GetNamedQuery ("GetBestStudent");
q.SetInt32 (0, someCourseId); // since the parameter has no name, you'll have to use the position of the parameter.
var result = q.UniqueResult<Student>();
相关问题