Using cascade in NHibernate
- by Tyler
I have two classes, call them Monkey and Banana, with a one-to-many bidirectional relationship.
Monkey monkey = new Monkey();
Banana banana = new Banana();
monkey.Bananas.Add(banana);
banana.Monkey = monkey;
hibernateService.Save(banana);
When I run that chunk of code, I want both monkey and banana to be persisted. However, it's only persisting both when I explicitly save the monkey and not vice versa. Initially, this made sense since only my Monkey.hbm.xml had a mapping with cascade="all".
<set name="Bananas" inverse="true" cascade="all">
<key column="Id"/>
<one-to-many class="Banana"/>
</set>
I figured I just needed to add the following to my Banana.hbm.xml file:
<many-to-one name="Monkey" column="Id" cascade="all" />
Unfortunately, this resulted in a Parameter index is out of range error when I tried to run the snippet of code. I investigated this error and found this post, but I still don't see what I'm doing wrong. I have the relationship mapped once on each side as far as I can tell. For full disclosure, here are the two mapping files:
Monkey.hbm.xml
<class name="Monkey" table="monkies" lazy="true">
<id name="Id">
<generator class="increment" />
</id>
<property name="Name" />
<set name="Bananas" inverse="true" cascade="all">
<key column="Id"/>
<one-to-many class="Banana"/>
</set>
</class>
Banana.hbm.xml
<class name="Banana" table="bananas" lazy="true">
<id name="Id">
<generator class="increment" />
</id>
<property name="Name" />
<many-to-one name="Monkey" column="Id" cascade="all" />
</class>