Wednesday, May 9, 2007

My default .NET data access strategy - NHibernate based approach

In my new project I and my team are being able to use a set of tools that I have been looking at for some time for data access in .NET. The approach is based on well know open source ORM framework: NHibernate, however, we are using other fantastic tools above it.

Instead of creating NHibernate mapping files, we are using Castle Active Record (AR) attributes to decorate our domain model classes. Analyzing the attributes AR can generate the mapping files dynamically, so we don’t have to deal with a lot of xmls files. We have something like this.

But we also don’t create the domain model directly, we use the Active Writer, which is a VS add-in that works like VS Class Designer, but it generates classes decorated with the AR attributes. So, it’s very fast to create a full domain model mapped using the AR attributes.

However, we don’t use the ActiveRecordBase class as base class for our model in order to avoid getting the persistence methods in our domain model. We prefer to use repositories (DDD flavor).

For the repositories we use a slightly modified version of Rhino Commons ARRepository (generic specialization). The implementation uses the ActiveRecordMediator which already have most of basic persistence operations, such as Save, Delete, FindAll, FindOne, etc.

For custom queries, we try to avoid using the NHibernate query API directly; instead we use the Ayende’s NHibernate Query Generator tool. It allows us to have strong typed queries that feels like SQL Queries, much better/natural in my opinion.

So, we have something like this in the EquipmentRepository:

Equipment FindDougEquip()
{
return FindOne(Where.Equipment.Name == “DouglasEquip” && Where.Equipment.Id > 0);
}


Well, I think this approach is very productive; we have a full persistable domain model and basic repository classes, besides the strong typed queries in few minutes. Really really fantastic open source tools.

1 comment:

Celia said...

Thanks for writing this.