Monday, 21 December 2009

Experiment in persistence ignorance

Having read a lot about how cool NHibernate is in helping with persistence ignorance, I decided to check if I can go far enough with it. More precisely, I decided to check if I can live without the Id property on my entities.

Now, you might ask, how do I show say products of a particular category. I mean, if I have a Web site, there should be some Url for it, and this Url should look like Products.aspx?CategoryId=1 or Products/List/CategoryId/1, whatever, but you should include the Id somehow. The answer is, you can always use session.Get() or session.Load() to get the entity by its Id, and the reverse is also true: you can use session.GetIdentifier() to retrieve the entity's Id.

At the same time, I switched from entities to models in my pages (WebForms or MVC). Doing this was a big relief because I felt myself dirty when adding a lot of properties to my entities just for the purpose of viewing (like, CategoryName, ItemCount etc). On the other hand, it means a lot of additional boring work: creating model classes and adding the mapping code. Fortunately, the first task is easy with the help of T4 templates, while the second is what AutoMapper (and other mappers) is created for.

Long story short, even though I managed to automate a lot, including the custom mapping code, I still got a lot of places where I had to repetively write session.GetIdentifier() in order to retrieve the Id. So, I'd recommend leaving it in place, although it doesn't seem to make much sense in terms of my domain.

Disclaimer: by entities, models and stuff I don't want to say that I'm doing DDD or any other cool stuff. The system is too simple for that. Nevertheless, separating models from entities, provided it doesn't require much effort, pays off in my case.