Posted by millionking on November 10, 2011
NHibernate is an open source Object-Relational Mapping (ORM) tool for the .Net platform… and the existing documentation and tutorials that I could find, whilst plentiful, are not aimed at those new to or inexperienced with ORM. This tutorial is based on using Visual Studio (I used 2008 beta 2) and Sql Server, however the database used is almost immaterial (one of the advantages of using an OR mapper).
If you already know what NHibernate and ORM are and you want to use it but just need to know how? Jump straight to the nitty gritty. Otherwise, read on.
WTF is ORM?
There is plenty of good stuff out there on what Object-Relational Mapping is, try wikipedia or the intro here (the tutorial is a bit out of date but the explanation is good) or there’s always Google.
However, in a nutshell, ORM is the process of mapping business objects (think OOP) to database relations (read tables). An OR Mapper is a tool that manages this process. There are several different OR Mappers available for .Net however NHibernate seems to have a lot of momentum and a good history as it is based on a port from the original Java version, Hibernate. The reason for using an OR Mapper is that writing SQL sucks, making changes is a pain in the ass and once you’ve started employing some decent OOP practices and are modelling your business domain with real-world objects, you don’t want to cloud your head with SELECTs, JOINs, WHEREs, primary keys, foreign keys and all that RDBMS jazz.
Okay… so what is ORM again?
Imagine you have a simple Contact class (which coincidentally we will do later). Wouldn’t it be nice if you could create a simple tbl_contact, write a little xml file that says “Contact.FirstName maps to tbl_contact.first_name” and then let something else worry about your CRUD (Create, Retrieve, Update and Delete) database logic? All you then have to do is say “Oi NHibernate, Save this Contact for me please”. That’s what you get with NHibernate and many other OR Mappers, it becomes the basis for your “Persistance Layer” or “Data Access Layer” for those who like their OOP terminology. You get to focus on your business objects and “proper programming” and you let NHibernate worry about saving stuff to the database.