In this article we will see that how you can retrieve objects and collections using the API provided by NHibernate.
Introduction:
In the last article we saw that how we can insert the data into the database using only few lines and without stored procedures. In this article we will look at some of the other cool features of NHibernate.
Retrieving a single record from the database:
You can easily retrieve a single record for a particular person based on the primary key. Just send in the primary key and you will be returned the object of the record.
private void Button1_Click(object sender, System.EventArgs e)
{ Configuration cfg = new Configuration(); cfg.AddAssembly("WebApplication1"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); Person person = (Person) session.Load(typeof(Person),1); Response.Write(person.Name); }
|
I have made the important line in bold. We are using session.Load method and sending the object type and the id of the object to pick up. In our database the id '1' belongs to 'Azam' and hence the object returned will contain information about Azam.
It is important to note that we are sending the 'PersonID' to the session.Load method and hence retrieving the live object. PersonID is also primary key in our database and an identity column. Since its an identity column we do not provide the set accessor in the PersonID property. But session.Load method requires that PersonID must have a set accessor in order to retrieve the record. In real application scenario you should have some other primary key like email or username so that you don't have to assign the identity column. |
Retrieving collection of objects:
You can also easily retrieve collection of objects. In the code below we are retrieving all the data from the table 'Person' and binding it to the datagrid.
private void Button2_Click(object sender, System.EventArgs e)
{ Configuration cfg = new Configuration(); cfg.AddAssembly("WebApplication1"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); IList personList = session.CreateCriteria(typeof(Person)).List(); DataGrid1.DataSource = personList; DataGrid1.DataBind(); } |
Retrieving objects based on Expression:
We can also retrieve objects based on Expressions. If we want to retrieve record of a Person whose name is 'Azam' we will just write something like:
IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.Eq("Name","Azam")).List(); |
In the above line we are simply adding an Expression just like the where clause in T-SQL. 'Eq' means Equal hence we are retrieving all the records where the property 'Name' is 'Azam'. It will return us with one record since there is only one record in the database with the name Azam.
You can also change the order of the rows retrieved. The order can be Ascending or Descending. In the code below I am retrieving the whole list and ordering them on the basis of the "Name" property in ascending order:
IList personList = session.CreateCriteria(typeof(Person)).AddOrder(NHibernate.Expression.Order.Asc("Name")).List(); |
If you have been working with T-SQL you should know that the 'IN' operator is one of the most important operators. Luckily we can use the 'IN' operator using NHibernate. The following code will return you the data of all the Person whose name is in the ArrayList. You can use any collection which implements the ICollection interface. I used Arraylist since it inherits the ICollection interface.
ArrayList myList = new ArrayList();
myList.Add("Azam"); myList.Add("Ali"); IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.In("Name",myList)).List(); |
You can also retrieve the results based on a certain range. Suppose you want all the people who work between two dates than you can use the following line.
IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.Between("DateStarted",
new DateTime(2005,01,01),new DateTime(2005,12,01))).List(); |
As you can see that now we are using the "Between" operator. There are lots of other operators that you can use depending on your need.
Please note that I have included two new properties "DateCreated" and "DateEnded" in Person.cs file which maps to the two new fields "StartDate" and "EndDate" in the database. |
Searching using NHibernate:
Searching is also very easy using NHibernate. Basically you just need to search in the collection and if the record with a particular search key is found you can take the appropriate action. In the code below we are searching for a Person name "Azam". If the person is found than a message is printed on the screen saying that "Person is found".
IList personList = session.CreateCriteria(typeof(Person)).List();
foreach(Person person in personList) { if(person.Name.Equals("Azam")) { Response.Write("Azam is in the list"); break; } else { Response.Write("Azam is not in the list"); } } |
You can also change the object properties and update it easily. Suppose that you want to change the date of the Person name "Azam" which is contained in the collection. Let's see how we can do this:
IList personList = session.CreateCriteria(typeof(Person)).List();
foreach(Person person in personList) { if(person.Name.Equals("Azam")) { person.DateStarted = DateTime.Now; person.DateEnded = DateTime.Now; session.Flush(); break; } else { Response.Write("Azam is not in the list"); } } |
As you can see above that we are simply finding the right person using the name property of the object. And than assigning the new Dates to the object and finally to make the changes we flush the session so that the changes appear in the database.
95% of all the operations that you can perform using T-SQL can be performed by using NHibernate classes.
Happy coding !