Tyler Murry
Tyler Murry

Reputation: 2815

One-to-Many List Not Being Saved with NHibernate

I'm very new to NHibernate, and I'm running into a problem while saving a list of child objects.

NOTE

<class name="Note" table="NOTE">        
     <id name="NoteID" column="NOTE_ID">
          <generator class="identity" />
     </id>          
     ...    
     <list name="Sections" table="NOTE_SECTIONS" cascade="all" lazy="false">
          <key column="NOTE_ID"/>               
          <index column="SORT_ORDER"/>
          <one-to-many class="Section"/>
     </list>
</class>

NOTE SECTION

<class name="Section" table="NOTE_SECTIONS"> 
     <id name="SectionID" column="Section_ID">
          <generator class="identity" />
     </id>      
     <property name="NoteID" column="NOTE_ID"/>
     ...
</class>

The mappings work perfectly for reading the data. However, when I make a change to the Note Section, The queries it generates appears to be going through the proper steps, but then I get the following error:

NHibernate.Exceptions.GenericADOException: could not delete collection: [Domain.Note.Sections#1][SQL: UPDATE NOTE_SECTIONS SET NOTE_ID = null, SORT_ORDER = null WHERE NOTE_ID = @p0] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'NOTE_ID', table 'NOTE_SECTIONS'; column does not allow nulls. UPDATE fails.

I have read that in order to save like this it will need to be bidirectional. But I've also read that bidrectional mappings don't work with Lists. It's important that my collection have a maintained order - what's the best way to save?

Upvotes: 1

Views: 977

Answers (2)

Cole W
Cole W

Reputation: 15303

You should use inverse="true" on your collection mapping if you wish to save child objects in this manner.

 <list name="Sections" table="NOTE_SECTIONS" inverse="true" cascade="all" lazy="false">
      <key column="NOTE_ID"/>               
      <index column="SORT_ORDER"/>
      <one-to-many class="Section"/>
 </list>

Inverse Attribute in NHibernate

Upvotes: 1

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

probably you would need to refer Note from Note Section as many-to-one relation.

Upvotes: 0

Related Questions