nhibernatemappingbacking-field

how do you name (and map) a backing property?


In a few cases, I have a property that needs a "backing property" for practical reasons.

For example, I have one type with a Name property - there is no transformation of the value happening on access, it merely triggers an action of some kind; a side-effect, if you will. (not that it matters for the sake of discussion, but in this particular case, the name gets copied somewhere else when changed.)

Let's say:

public class Person
{
    private string __name;

    protected internal virtual string _name
    {
        get
        {
            return this.__name;
        }
        set
        {
            this.__name = value;
        }
    }

    public virtual string Name
    {
        get
        {
            return _name;
        }

        set
        {
            _name = value;

            // action when changing the name takes place here...
        }
    }
}

So the "_name" property is mapped to the database, but is kept protected/internal so that it cannot be modified directly. And the second public property "Name" provides the actual access.

The reason I have it set up this way, is because if that action was built directly into the mapped "_name" property's set-method, it would be triggered when an object is hydrated from the database, which is not what I want.

This all works fine as such.

The problem is, when you need to query this type, attempting to query Person.Name won't work, because that property isn't mapped!

What I dislike about this, is the fact that you're writing code against Person.Name, but have to write queries against Person._name, which is error-prone and confusing.

Is there a better way to solve this problem?


Solution

  • Can you use nosetter.camelcase-underscore for the access in the mapping? This would set the field directly (if named correctly, eg _name) instead of using the property setter.

    eg:

    <property name="Name" column="Name" type="String" access="nosetter.camelcase-underscore"/>