NHibernate
Simplistic "get started" code for NHibernate (version 1.2, 2 and 3).
- Download the latest version from NHForge.org
- In your data access layer, reference the NHibernate.dll
- Optional extras include Fluent mapping and NHibernate.Caches
- From v2.1 up to 3.2, add the proxy generator such as Castle- after v.3.2 it's built in
- For version 2 consider Lambda Extensions (it's superceded in v3).
- Create the configuration (contains connection string).
- Create the domain entities. Entities are mostly POCOs but you probably should inherit from a base class for identity.
- Create the mapping to the database tables (in hbm.xml or use Fluent mapping)
- In Application Start create the session factory (don't create it for every session or operation).Simplest is to hold it in a static or singleton object such as a SessionManager.
- Open an ISession from the Session Factory (in asp.net you may use an IHttpModule; in MVC a global ActionFilter). Use Load/Get/SaveOrUpdate etc- then Flush/Commit to database. In asp, typically create a session with a begin request, but you could store it in Session to span requests ("conversations"). Ideally create repositories (data access objects) for each domain entity, using the SessionManager.
For quick-start database-driven NHibernate, check out my Database schema reader which has a simplistic code generator.
Example Domain
Here we just use Category and Product from Northwind.
- Sample entities
- EntityBase - a base class overriding GetHashCode and Equals.
- Sample hbm (and fluent) mapping
- ProductRepository
Here are the same entities in ActiveRecord- the mapping is done by property attributes.
NHibernate helpers
- App.config - minimum required settings. And Fluent configuration in code.
- SessionManager - configure NHibernate and create sessions
NHibernate helpers - optional
- GenericRepository
- TransactionRequired- transaction wrapper
- IHttpModule for hooking up asp.net
- UnitOfWork - an IDisposable wrapper
- Unit test - putting it together