nhibernatenhibernate-mappinglinq-to-nhibernate

HBM mapping both field and property


I have the following class:

public class Foo 
{
    //...
    protected int? someData;
    public int? SomeData
    {
        get {return someData;}
        set {someData = value;}
    }
    //...
}

This class is mapped in HBM file:

<class name="Foo" table="Foo">
//....
    <property name="someData" access="field" column="SOME_DATA" />
//....
</class>

For legacy reasons, the columns were mapped to a fields (lowercase), which are unaccessible (not public properties - uppercase).

These lowercase mappings are using multiple times in the project as part of HQL strings, criteria-based queries and so on. It is close to impossible to find all usages.

The problem is that such usage makes it impossible to use even on simple lambda:

session.Query<Foo>().Select(f=>f.SomeData)

throws error, as uppercase "SomeData" is not mapped, and

session.Query<Foo>().Select(f=>f.someData)

does not compile, as lowercase "someData" is protected.

What happens, if I will map BOTH field and property:

<property name="someData" access="field" column="SOME_DATA" />
<property name="SomeData" access="property" column="SOME_DATA" />

I tried quickly, and it seems to work, but will it have any drawback?

Is there any other simple solution, that will not require editing every criteria-based query in project?

Thanks for any help.


Solution

  • You can map the same column multiple times but with recent NHibernate versions only one of the properties need to be mapped as modifiable. So just add insert="false" update="false" to your additional mappings to avoid any issues in future:

    <property name="someData" access="field" column="SOME_DATA" />
    <property name="SomeData" access="property" column="SOME_DATA" update="false" insert="false" />