In this article, i will create a simple application that implent NHibernate, and in database side, i will use SQL Server 2008. What is NHibernate ? I will not explain it in there, so many explanation what it is in internet, like in here.
You can download latest NHibernate version here.
First, i will create a simple database that have just one table (and i added some record in there):
This is the DDL
Hmm.. what is Identity(1,1) mean ??? It is mean we will set ACCID attribute, the primary key, to become autonumbered, the value will be added automatically incrementing from 1, 2, 3, … and so on.
Next step, we will create simple solution in Visual Studio 2008 SP1 (remember … to connect to SQL Server 2008, your Visual Studio 2008 must be Service Pack 1 ).
Add some references
- NHibernate.dll (NHibernate library)
- NHibernate.ByteCode.LinFu.dll (for lazy loading)
Test your connection with database using Server Explorer
Do not forget to copy the connection string…
For my example, my database connection string is : ]
Data Source=WIRTH;Initial Catalog=TestNHibernate;User ID=azer89;Password=azer89
Nexttt !!!! create an App.config file in your project (Just Right click your project, Add, New Item, and Application Configuration File)
Set your App.config like this :
You must pay attention in property connection.connection_string and dialect in code above. Add a model class similar to Account Table, its fields must be similar too
Your Account.cs should be like this :
After creating Account class, we will create map to Account Table using XML file, so NHibernate will know that Account class in application will map to Account Table in database. The XML filename will be “Account.nbm.xml”
Look at generator class, its value is “native”, it is because we have set ACCID column into autoincrement. Oh yeah, Build Action for hbm.xml file must be “Embedded Resource”
Next step is to create persistence class, we will name it NHibernateHelper.cs
Since ISessionFactory is expensive to create (it almost take one second in my computer !!!) we will create one object of ISessionFactory, otherwise with ISession, it is very cheap to create, so we can create it very ofter in your application. We will test the code :
It is Work !!!