8

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 ?

2 Answers 2

9

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>();
}
Sign up to request clarification or add additional context in comments.

3 Comments

actually the SetResultTransformer thing does not work for me ... I get an error message saying : Error - NHibernate.PropertyNotFoundException: Could not find a setter for property 'Manufacturer' in class Product .............. ( This is somehow true as I don't have a property Manufacturer in the class product; the property is called ManufacturerName ; the nhibernate xml mapping specifies that ManufacturerName prop. maps to the Manufacturer column in the table )
Instead of select * you can specify the columns you want from the product table. This way SetResultTransformer will work.
@sh_kamalh I specified all columns and I still got the same error
4

Yes you can. Check out Entity Queries using Native SQL : http://codewut.de/content/using-native-sql-nhibernate

2 Comments

The link does not work any longer. "This content is no longer available on Knol."
Here's another. codewut.de/content/using-native-sql-nhibernate Or just google "Entity Queries using Native SQL NHibernate" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.