NHibernate Many-To-Many Issues and Solution

I was having a few issues with NHibernate Many-To-Many relationships, I was trying to link sample types with physical locations via a many-to-many so you could not put a sample into a container that did not allow it’s type.

I initially set this up using a single many-to-many mapping on the Physical Location side with inverse set to true

<bag name="LimitedTypes" inverse="true" lazy="true" cascade="none" table="pLocLType">
      <key column="pLocTypeid" />
      <many-to-many class="spring.pxl.Domain.SampleType,spring.pxl.Dao" column="typeid" />
</bag>

While in initial testing this worked when I manually entered data into “pLocLType” table I could pull our of the pLocLType object all the links, and this worked, however when running integration tests, I found that if I added an element to the [LimitedTypes] IList the field in the database was not being populated when I saved it. Time to look at the relationship again.

After a bit of tinkering I came across my problem, I needed the mapping in both the  pLocLType mapping file and the SampleType mapping file, I also needed to have inverse=”true” on only one of the bags. Which makes sense considering what inverse means, it is nHibernate’s way of fobbing off responsibility to another class, but if you have them both set to true, then object 1 says object 2 should do it and object 2 says object 1 should do it and in the end nothing gets done.

<bag name="LimitedTypes" lazy="true" cascade="none" table="pLocLType">
      <key column="pLocTypeid" />
      <many-to-many class="spring.pxl.Domain.SampleType,spring.pxl.Dao" column="typeid" />
</bag>
<bag name="LimitedPlocs" inverse="true" lazy="true" cascade="none" table="pLocLType">
      <key column="typeid" />
      <many-to-many class="spring.pxl.Domain.SamplePLocType,spring.pxl.Dao" column="pLocTypeid" />
</bag>

This however worked and the integration tests could continue.

kamui