Search code examples
c#nhibernatehqlcastle-activerecord

NHibernate with Castle, HQL could not locate parameter [param]


I have an HQL query on a class mapped with Castle ActiveRecord and get the following error: NHibernate.QueryParameterException: could not located named parameter [param].

Here's my class, simplified:

[Serializable]
[ActiveRecord("my_table", Schema = "my_schema", UseAutoImport = false, Mutable = false)]
public class MyTable : MyServerActiveRecord<MyTable> //Extension of ActiveRecordBase<>
{
    [PrimaryKey(PrimaryKeyType.Identity, "my_pk")]
    public int ID {get;set;}

    [Property("my_column1")]
    public int MyColumn1 {get;set;}

    [Property("my_column2")]
    public int MyColumn2 {get;set;}
}

And the method with my HQL

public static int GetSum(int num1){
    IQuery query = session.CreateQuery(@"
        select sum(case when t.MyColumn2 = 2 then 1 else 0 end)             
        from My.Complete.Namespace.MyTable t 
        where t.MyColumn1 = :num  
        group by t.MyColumn1 
    ");
    query.SetParameter("num", num1);
    return query.UniqueResult<Int32>();
}

Using SetInt32 instead of SetParameter didn't work. I verified the spacing in the query.

The query works fine if I throw a 7 where :num is and cut out :num and its set statement entirely.


Solution

  • So I was populating my session variable like this:

    session = ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof(T)).OpenSession();
    

    where T = the query return type, aka Int32.

    I changed T to be the class I was querying on, MyTable, and everything started working. Bummer that Castle/NHibernate doesn't return a more helpful error. My bad for not including the session line in the question.