If I were designing a database from scratch, I’d avoid nullable columns like The Plague. Unfortunately, a lot of legacy (and not-so-legacy) databases tend to have nullable columns. Kinda sucky if you’re doing NHibernate development under .NET 1.1 because you have to have to do a extra stuff to make it work.
In preparation for my NHibernate talk at VSLive San Francisco, I needed to learn how to actually map that scenario. Then I started thinking about the new nullable value type syntax in .NET 2.0 (int? myInt32 = null; DateTime? myDateTime = null;) and wondering well how that would work with NHibernate.
So, I wrote up some unit tests and some sample classes to try it out.
The .NET 1.1 way using the NHibernate nullable DLLs was a lot easier to work with than I expected. Any value-type property on your entity classes just needs to be the appropriate type from Nullables.dll (ex. DateTime –> NullableDateTime, int –> NullableInt32) and in the mapping file you have to add a “type“ attribute to the appropriate “property“ elements.
The nice thing is that when you access the properties on your entity classes, you really don’t have to be all that aware that they’re anything other than the regular .NET value type. You can just assign to them and compare them pretty much as normal…no mucking around with new‘ing up instances of Nullable types in order to do assignments. Example: temp.NullableBool = false;
The .NET 2.0 way is even less intrusive. In your entity classes, mark the property datatype as nullable using the “?“ syntax and in your mapping file you don’t have do anything special at all. It just works.
Anyway, I’ve posted the test project and sample classes are here. Make sure to check the database connection string in “hibernate.cfg.xml“ in the NHibernateResearch.VisualStudioTests project. Also, since the tests do drop and create database tables, you might want to create a blank database and point hibernate.cfg.xml’s connection string to that new database.