NHibernate Query object collection issue
I am new to NHibernate and need some information regarding the internal working of the engine:
I have a table called Student and the design is as follows:
RollNo
Name
City
Postcode
and there are 5 more columns like this. I have School class and mappings associated with it.
I am querying RollNo and Name using session as given below:
IQuery query = session.CreateQuery("SELECT RollNo,Name FROM Student);
Executing query.List resulting in error because the query is returning object[][].
Now, I changed t开发者_如何转开发he query as given below:
IQuery query = session.CreateQuery("FROM Student);
Executing query.List on this query yeilds the desired results. But, the results contain more data than I want.
Could you please let me know the query to which I can get RollNo and Name from Student and castable as Student collection.
Thanks, Mahesh
I think that you may be mixing up querying columns of a database and querying objects. when you set up your mapping for the student object you specified that to represent a student it must contain certain properties. when you query based on that object you will get back whatever your mapping specified as the properties for the student.
Having said that it is possible to query the database and return the only the data you want to a new object.
//Domain Object
public class StudentLite
{
public StudentLite(int rollNo, string name)
{
this.RollNo = rollNo;
this.StudentName = name;
}
public virtual int RollNo {get; set}
public virtual string StudentName {get; set;}
}
//DataAccess Layer
IList<StudentLite> = Session.CreateQuery("SELECT new StudentLite(RollNo,Name) FROM Student").List<StudentLite>();
I guess it would be possible to provide a constructor on the student object similar to the constructor here and do the same thing for the student object. The problem that I see with that approach is that you may try and use the student object when it has not been fully hydrated and try to access the other properties like City and Postcode and get unintended results.
精彩评论