NHibernate one-to-many not saving children

1.1k views Asked by At
class A {..} 
class ContainedA { property of type A and some extra information }
class B : A { collection of type ContainedA  }

As you can tell the idea is to be able to contain a single instance of A in several B's, B itself is also of type A only it can hold other A's

A and B's mapping

  <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="REDACTED"
    assembly= "REDACTED">

    <class name="A" table="A" discriminator-value="1">
        <id name="Id" column="Id" type="int" access="field.camelcase-underscore">
            <generator class="identity" />
        </id>

        <discriminator column="Type" type="int"/>

        <subclass name="B" extends="A" discriminator-value="2">
            <bag name="ContainedAs" cascade="all">
                <key column="AInternalId"/>
                <one-to-many class="ContainedA"/>
            </bag>
        </subclass>

    </class>
</hibernate-mapping>

The mapping for ContainedA

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="REDACTED"
    assembly= "REDACTED">

    <class name="ContainedA" table="ContainedA">
        <id name="Id" type="int" access="field.camelcase-underscore" column="Id">
            <generator class="identity" />
        </id>
        <many-to-one name="A" class="A" column="ContainedAInternalId" cascade="save-update"/>
        <property name="SomeOtherInfoString" column="SomeOtherInfoString" not-null="true"/>
    </class>
</hibernate-mapping>

My issue is that when I save the container B it's not saving it's ContainedAs collection and not the actual A's contained. This is supposed to be robust, B can be assigned both existing and none existing As and i want to perform a single session.Save(B) and have everything saved.

Your help in the matter would be greatly appreciated.

EDIT: found an error in one of the original HBM's fixed it, still not working

2

There are 2 answers

0
DorD On BEST ANSWER

This isn't a complete answer, rather a workaround which resolved the issue.

(Copied from my comment)

"I've somewhat resolved the issue by moving the bag from B to a concrete subclass mapping, in my code B is a base subclass itself that has two different implementation, apparently Nhibernate just ignored the bag because it was on a subclass base mapping."

1
Jamie Ide On

You need to show the code in addition to the mapping. But I notice that you don't have the inverse attribute set. The inverse attribute defines which side "owns" the relationship. It's a bit counter-intuitive, but you set inverse="true" to declare that the other side owns the relationship.

A typical one-to-many relationship is mapped so that the many side is the inverse side. With that mapping, it's necessary to both add the contained object to the collection (one side) and set the reference to the containing object on the object one the many side.