2010-02-22 31 views
0

我收到以下錯誤:「消息:沒有爲一個或多個必需參數給出值。」當我嘗試從MBUnit測試代碼時。如何爲NHibernate命名查詢中的參數提供值

<?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; 
     } 
    } 
} 

如何提供命名查詢需求的價值?

回答

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

OK完美....讓我怎麼提供的參數值? – MadSeb 2010-02-22 13:59:55

+0

挑戰在於,由於某些原因,我無法從代碼中訪問「會話」......所以我必須從映射中設置參數......以任何方式執行此操作? – MadSeb 2010-02-22 14:03:35

+0

SELECT * FROM BestStudents WHERE CourseId = 5 – Will 2010-02-22 15:48:25

相關問題