Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while conversion of Nhibernate query to generic list

I have a simple entity called EmployeeEntity with properties ID, Name, Age, Organisation, and Designation. I am just querying the database using the query

IQuery query = session.CreateQuery(
    "select Name, Designation, Age, Organisation FROM EmployeeEntity " +
    "group by Name, Designation, Age, Organisation");

IList<EmployeeEntity> employee = query.List<EmployeeEntity>(); // Throws error

but on conversion to my type, it's throwing an exception:

Could not execute query[SQL: SQL not available]

with InnerException:

The value "System.Object[]" is not of type "NHibernateTest.EmployeeEntity" and cannot be used in this generic collection.
Parameter name: value

though it works fine using this query:

IQuery query = session.CreateQuery("select e FROM EmployeeEntity e group by e");

IList<EmployeeEntity> employee = query.List<EmployeeEntity>();

but I don't want to select all the columns because I don't need them.

like image 260
pijush Dutta Avatar asked Mar 29 '11 14:03

pijush Dutta


2 Answers

If you only want a certain set of columns, create a class that maps one to one with your columns. Like so:

public class EmployeeView
{
    public string Name { get; set; }
    public string Designation { get; set; }
    public int Age { get; set; }
    public string Organization { get; set; }
}

You then just need to add a result transformer to your query

IQuery query = session
    .CreateQuery("select Name ,Designation ,Age ,Organisation  FROM EmployeeEntity   group by  Name ,Designation ,Age ,Organisation")
    .SetResultTransformer(Transformers.AliasToBean<EmployeeView>());

Ilist<EmployeeEntity> employee= query.List<EmployeeView>();
like image 124
Vadim Avatar answered Nov 12 '22 20:11

Vadim


When you're querying with select Name, Designation, Age, Organisation..., NHibernate will actually return an IList<object[]> instance. To overcome this, try rewriting your HQL to select new EmployeeEntity(Name, Designation, Age, Organisation)... and add an appropriate constructor to EmployeeEntity class.

like image 30
Anton Gogolev Avatar answered Nov 12 '22 20:11

Anton Gogolev