NHibernate and Auto Properties

I’ve been working through the NHibernate with ASP.NET ProblemDesignSolution (Wrox Blox), with some small changes. I’m writing my sample in C# using the .Net framework 3.5. I prefer to use auto-properties.

It’s common that fields have private setters and only nhibernate can map using the backing field (set via reflection).

public String City { get; private set; }

The problem is telling NHibernate how to find the backing field. When you have an explicit field, you end up with something like:

<property access=”field.camelcase-underscore” name=”City” />

But with no backing field, that is a problem. I started looking around on the net and found the following:

StackOverflow discussion without much good info
and a blog post with an interesting response from Ayende Rahien.

Ayende is saying to not worry about the issue, NHibernate will still be able to set via reflection. That’s fine, but it feels a little “magical”, especially to a new developer coming along.

Why not set protected? It’s not unreasonable to expect a maintaining developer to understand that NHibernate sub-classes your class.

public String City { get; protected set; }

Now the mapping stays simple too:

<property name=”City” />

And there is no need to expect a maintaining developer to know that reflection magic is setting the property.