Using cascade in NHibernate

Posted by Tyler on Stack Overflow See other posts from Stack Overflow or by Tyler
Published on 2011-01-16T03:26:35Z Indexed on 2011/01/16 3:54 UTC
Read the original article Hit count: 379

Filed under:
|
|

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>

© Stack Overflow or respective owner

Related posts about c#

Related posts about nhibernate