Wednesday 20 January 2010

Many-to-one and Composite-id mapping with NHibernate

Nhibernate's reference documentation sometimes leaves something to be desired. I was looking for the correct syntax to map a which has a and the documentation did not discuss it and a google search revealed nothing. While poking around the 'nhibernate-mapping.xsd' i found out that the element supports having elements underneath it so as to have the following syntax


<many-to-one name="Foo">
  <column name="FK_Column1">
  <column name="FK_Column2">
</column>


where the Foo class is mapped as
<class name="Foo" table="Foo">
  <composite-id class="FooCompId">
    <key-many-to-one name="SomeEntityA" column="PK_Column1">
    <key-many-to-one name="SomeEntityB" column="PK_Column2">
  <composite-id>
  ....
</composite-id>


note here that the Foo class uses 2 properly mapped classes (SomeEntityA and SomeEntityB) hence the <key-many-to-one/>
interestingly i used this as part of a <subclass /> element and it worked normally.

And to map a <bag /> of "Foo" from an other entity this syntax worked

<bag name="Foos" inverse"true">
  <key>
    <column name="FK_Column1">
    <column name="FK_Column2">
  </key>
  <one-to-many class="Foo" />
</bag>

the only requirement is that the order of the columns declared must match the order of the <key-many-to-one/> declared in the composite-id

1 comment:

  1. Thanks so much!

    I've tried a lot of tutorials but any of them explained that the order of the columns declared must match the order of the declared in the composite-id.

    Thank you again.

    ReplyDelete