So you want to learn NHibernate – Part 0.5, Prerequisites (or NHibernate = Marijuana.NET)

July 31, 2008

NHibernate is an Object Relational Mapper (ORM) tool – which is to say it takes your living, squirming objects from a running application and stuffs them into some kind of database. It also will be happy dig into the database, grab some sleeping object, shake it awake and toss it back into your running application when you need it.

As a standalone tool, this can be very useful. It saves you writing a metric ton of SQL, it saves you from having to type out a bunch of tedious boilerplate ADO.NET code to execute that SQL and then find something useful to do with the awkward, pointy data sets and data tables and data readers that are returned.

You can get a lot of mileage from just learning how to use NHibernate, replacing your existing data access code, and leaving it at that. Taking that approach, though, would be leaving a great deal of what NHibernate has to offer on the table. ORM’s such as NHibernate, very much like Inversion of Control containers, are components of a particular kind of loosely coupled, domain centric application design that is all the rage these days (though for very good reasons) called Domain Driven Design (DDD).

For the uninitiated, wholesome, mamma’s boy Microsoft developer picking up a tool like NHibernate or an Inversion of Control Container like Castle Windsor  can often be the first step towards experimenting with Domain Driven Design (championed by the ALT.NET community), introducing you to a different kind of crowd that does things in a different kind of way, much like smoking Marijuana is considered the "gateway drug" to other, "harder" drugs. In the same way that smoking a Marijuana cigarette while listening to your favorite Jazz records with some new friends on Saturday will often lead you to snorting lines of cocaine off of the floor of a public bathroom in a Tijuana brothel on Sunday, learning and using tools like NHibernate will often lead you towards learning a more maintainable, more flexible and generally more fun way of building your software systems.

In concert with Inversion of Control containers, NHibernate supports the concept of "Persistence Ignorance" (PI) – which more or less means that your domain objects have no idea where, how or even that they are being persisted. This dramatically reduces the coupling of your business logic to its infrastructure, which dramatically increases its maintainability, reusability and ultimately its life span. I’m no expert in this field, so I’ll leave it to the experts to do the teaching, but I do feel pretty strongly that before (or in parallel with) learning NHibernate, or any other ORM, it is important to also learn about the kind of architecture it was designed to serve. The resources below should be a very good start:

1. Foundations of Programming – a free e-book by Karl Seguine
This should really be called "An introduction to the ALT.NET approach to Domain Driven Design and Test Driven Development" – it is far more of an introduction to a particular style of building software(despite the "how memory works" chapter) that it is to the foundations of programming in general, but nevertheless it is a very easy to read, very humbly written and very useful introduction to writing modern enterprise software using .NET. If you’re already a grizzled ALT.NET warrior, well you aren’t reading this post, and you probably won’t get much out of this book, but for those of us that don’t fit into that category, I highly suggest reading this short, concise introductory text.

2. Domain Driven Design Quickly
This is a summary of Eric Evan’s seminal book on Domain Driven Design (which you should also read) in the form of a free e-book. This book will get you out of the starting gate. This is much longer than the Foundations of Programming e-book, so you may want to print it out on the old laser jet and take it home.

3. Onion Architecture Part 1, Part 2 and Part3
The name, perhaps, is rather silly, but Jeffrey Palermo does a very nice job of describing how an ideal DDD architecture should be constructed, and how application layers should communicate with one another in contrast to more traditional n-tier architecture.

4. Default Architecture: Layers
A less accessible but still useful post describing how Ayende Rahien (author of Rhino Mocks) approaches his application architecture.

5. NHibernate Best Practices with ASP.NET, 1.2nd Ed.
Despite the title, in this article Billy McCafferty talks quite a bit about application architecture especially as it relates to ORM, Persistence Ignorance and NHibernate, and is definitely worth reading. He has an updated reference architecture which he calls S#arp Architecture, and it is available on Google Code, along with some documentation that contains a hidden gem of morbidly dark humor that is beautifully out of place with the style of the article. I’ll let you find it yourself, but the guide is a good read.

6. Object Relational Impedance Mismatch
This is a useful concept to understand before diving into using an ORM for the first time as well, as it is the Object Relational Impedance Mismatch that NHibernate or any other ORM exists to solve. (For a mild debate/discussion of this see this post and this one). In a nutshell, the "impedance" mismatch is the vast conceptual and structural difference between an object oriented domain model and a table-oriented, set-based relational database. Cramming OO objects into a relational database and the difficulties doing so are the OR Impedance mismatch. FYI, the term "Impedance Mismatch" comes from the EE world, where "impedance" is the resistance of a system to the flow of energy. If energy is to flow consistently from one system to an
other when two systems are connected together, then their "impedance" must be matched or bridged. I suppose in the case of a software system the "energy" is the representation of the state of the domain, and for that representation to flow consistently in between the boundary between an object graph and a relational data store, both with very different levels of resistance to the state representation (the object model having the far smaller impedance)  a mechanism is required to bridge or match the impedance of the two systems, and in the case of NHibernate that mechanism is the ORM toolset.

In the next post I’ll provide specific links to NHibernate resources that I’ve found to help actually learn the tool.

So you want to learn NHibernate – Part 0, Overview

Why?
For the past several years we have been using a home grown ORM tool as part of a larger application framework. It works pretty well, but there are a few drawbacks:

  • It’s home grown – unless we divert attention from building our business applications, it stays frozen in time. This is a drawback of every home grown tool, and why a community or third party library should always be considered when good ones are available.
  • It’s tied to SQL Server. Getting it to run on another database platform would be quite a bit of work.
  • No LINQ support, in fact, no query language of any kind. When we want custom queries, we put them in our model editor and generate new code. This get’s us a method on our DAL to execute the query, but that means there is this whole open-model-editor, make change, generate code, compile code and test cycle for every little query we may need.
  • As an internal tool, it is rather poorly documented. Training new developers requires using in-house staff. No pointing to a list of links on the web and saying, “here, go learn this and we’ll get started”
  • It means nothing when you put it on a resume :)

As we are embarking on a new set of projects, the time seems right to consider the possibility of moving to a mainstream ORM tool with a healthy community and plenty of learning material. I won’t go through the selection process, but we looked at some commercial tools and we looked at NHibernate, and while the commercial tools have some nice polish on them and comprehensive documentation, the community surrounding NHibernate is so vibrant (and so distinguished) that we’re strongly leaning in that direction.

NHibernate does lack some polish. It’s an engine that requires some build-out of infrastructure to make it comfortable to use, but much of that build out has been contributed by community members and where it hasn’t, the blogosphere has filled the gaps with any number of helpful walk-through’s and best practices posts. I’ll post links to the resources I’ve identified in a subsequent post.

Active Record
Perhaps the most prominent of these community contributed build-outs is the oh-so-famous ActiveRecord implementation that is part of the Castle Project. NHibernate, in its raw, unprocessed form, handles persisting Plain Old CLR Objects (POCO’s) to a persistence medium by way of XML mapping files which must be hand crafted. The mapping file contains which fields of a persistent object will be stored to the database, and can control every detail of the mapping between a field and a corresponding database column. The mappings also communicate to NHibernate how entities relate to one another, such as many-to-one, many-to-many, etc.

All this is very powerful, but perhaps not so much fun to manage (although many people prefer to do so manually). Active Record is a design pattern for object relational mapping that maintains one Class for each Table in a data store, more or less, and Castle Windsor provides an implementation of this pattern such that a combination of Convention over Configuration and .NET Attributes remove the need for creating and maintaining NHibernate mapping files. In fact, when you use Castle’s ActiveRecord, you may not know you’re using NHibernate at all as the whole experience is nicely abstracted. To make this happen it is understood when you use Active Record your objects will be saved to the database in a certain way, and you are OK with that, because it saves you many small decisions and many XML code edits.

Whether or not to use ActiveRecord is, I think, largely a matter of taste and your personal relationship with Convenience(Cost) vs Control, the yin and yang of the Build vs Buy decision. We haven’t settled on ActiveRecord yet, although we are pretty sure that if we don’t use ActiveRecord, we’ll be rolling our own code generator to maintain both NHibernate Mapping Files and the Database Schema, and possibly the Entity classes themselves, based on a metadata model. Maintaining a few trillion XML mapping files doesn’t sound like a lot of fun to me.

Next I’ll talk a little about architecture, and then drown you in NHibernate hyperlinks.