Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: Get object by SQL Query

Tags:

sql

nhibernate

Is it possible to do something like this in NHibernate?

Product GetSpecificProduct()
{
    return session.CreateSQLQuery("SELECT * FROM Products WHERE price =
        $500").UniqueResult<Product>();
}

When I try to run this code I get:

System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type Product.

Or do I have to use the NHibernate query language ?

like image 744
MadSeb Avatar asked Nov 27 '10 11:11

MadSeb


1 Answers

If you have to use CreateSqlQuery, you can use the following:

Product GetSpecificProduct()
{
   ISQLQuery query = session.CreateSQLQuery("SELECT * FROM Products WHERE price = $500");
   Product p = query.SetResultTransformer(Transformers.AliasToBean<Product>()).UniqueResult<Product>();
}

I suggest you better use ICriteria as in:

Product GetSpecificProduct()
{
   ICriteria c = session.CreateCriteria();
   c.Add(Expression.Eq("Price", 500));
   return c.UniqueResult<Product>();
}
like image 158
sh_kamalh Avatar answered Oct 21 '22 08:10

sh_kamalh