views:

304

answers:

1

Hi,

I'm trying to learn about SQL named queries using NHibernate and I have the following code. The issue is that I get the following error : "Message: No value given for one or more required parameters." when I try to test the code from 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>

The code for the entity is:

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  A: 

The error says it all: you retrieve the named query, and want to execute it. Although, as you can see in your code, the named query has a parameter in its where clause. You have to provide the named query with a value for its parameter, otherwise it cannot be executed.

Something like this:

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>();
Frederik Gheysels
ok perfect .... so how do I provide the value for the parameter ?
MadSeb
the challenge is that I do not have access to "session" from my code for some reasons ...... so I have to set the parameter from the mapping ...any way to do it ?
MadSeb
SELECT * FROM BestStudents WHERE CourseId = 5
Will
If you have no access to NHibernate's session (ISession), then, how can you retrieve the named query ?How can you even work with NHibernate , if you have no access to the most important part of NHibernate ?
Frederik Gheysels
I want to retrieve the named query by using the entity ... UniversityCourse course = _database.UniversityCourses.Get(ID) ......and I want to be able to refer to course.BestStudent ....does it make more sense now ?
MadSeb