The danger of duplicated mapping of many-to-one in NHibernate

If you use NHibernate, you will often have to deal with lots of many-to-one mapping. However, if you are not careful, you might accidentally create duplicated mapping due to the use of foreign key.

Let's say you have a class, A, which has a column, A_ID as the primary key. Class B is related to A via a column, A_ID (in B), which is the foreign key referencing A's primary key. Hence, we would define our B object like the following,

public class B
{
   public virtual A ClassA { get; set; }
    
   public virtual long A_ID { get; set; }
}

We have both the properties to represent the object A (due to the foreign key mapping), as well as the column which acts as the foreign key. The following is the XML mapping file.

<property name="A_ID">
      <column name="A_ID" not-null="true" />
</property>

<many-to-one name="ClassA" column="A_ID" cascade="save-update"/>

We want to get a reference of A, as well as the column A_ID. However, if we try to execute our code with the above mapping, we would get an error, System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index. The main reason is that we are mapping two properties against the same column, and it would trigger the error mentioned. In case we are just interested in querying the same column, both as a property and object, we need to add attributes to let NHibernate ignore one of them during insert & update operation.

<many-to-one name="ClassA" column="A_ID" cascade="save-update" insert="false" update="false"/>

This would solve the error above. Hope it helps!

Comments

Popular posts from this blog

ASP.NET Core service locator pattern

Caching and generic query using NHibernate [.NET Core]

Ways to perform eager loading via NHibernate