0

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?

mindplay.dk
  • 7,085
  • 3
  • 44
  • 54

1 Answers1

0

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"/>
TomMhC
  • 133
  • 6
  • So this maps the backing field directly, and doesn't require a property as such? (is there a penalty or other side-effects from doing that as opposed to mappping a property?) – mindplay.dk Dec 22 '11 at 16:08
  • Yes, exactly. There are no penaltys - this is the preferred way to map properties exactly because it avoids side effects with code in the property getters/setters. – TomMhC Dec 22 '11 at 16:14
  • 1
    By the way, I don't think "nosetter" avoids side-effects with getters, only getters, isn't that right? You'd have to use "field" access to also avoid getters, or not? (not that getters should ever cause side-effects) To others researching this stuff, the following post was also incredibly useful: http://stackoverflow.com/questions/2339264/property-access-strategies-in-nhibernate – mindplay.dk Dec 22 '11 at 16:26