views:

121

answers:

1

I don't understand why NHibernate is trying to insert the parent object - when the row already exists in the db - when I'm inserting the child row.

Parent mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
<class name="ReportDistribution.Client.ReportMgr.Model.ClientReport, ReportDistribution.Client.ReportMgr.Model" 
     table="ClientReport" 
     lazy="false"
     dynamic-update="true">
<id name="Id" access="property" column="ReportID">
  <generator class="assigned"></generator>
</id>
<property name="MaxAge" access="property" />
<property name="DeleteUnread" access="property" />
<property name="Description" access="property" />
<property name="Name" access="property" />
<bag name="ClientPublications" cascade="all" lazy="false">
  <key column="ReportID" />
  <one-to-many class="ReportDistribution.Client.ReportMgr.Model.ClientPublication, ReportDistribution.Client.ReportMgr.Model" />        
</bag>
</class>  
</hibernate-mapping>

Child mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
<class name="ReportDistribution.Client.ReportMgr.Model.ClientPublication, ReportDistribution.Client.ReportMgr.Model" 
   table="ClientPublication" 
   lazy="false"
   dynamic-update="true">
<id name="Id" access="property" column="PublicationID">
  <generator class="assigned"></generator>
</id>  
<property name="CreatedOn" access="property" type="DateTime"></property>
<property name="IsMarkedForDeletion" access="property"></property>
<property name="IsDeleted" access="property"></property>
<property name="HasBeenRead" access="property"></property>
<property name="ReceivedOn" access="property" type="DateTime"></property>
<property name="FileExtension" access="property"></property>  
<property name="IsDownloaded" access="property"></property>
<property name="MustRead" access="property"></property>
<many-to-one    
  name="Report"
  class="ReportDistribution.Client.ReportMgr.Model.ClientReport, ReportDistribution.Client.ReportMgr.Model"
  lazy="false"
  column="ReportID">
</many-to-one>
</class>
</hibernate-mapping>

The Parent class (Report) has property which is a collection of child classes. The Child class (Publication) has property which is the parent object.

Thanks in advance....

A: 

It sounds to me like the parent object is no longer connected to the session when you are saving the child. HNibernate tracks the state of entities that are connected to a session, but if the entity becomes detached it loses the ability to track state.

Think of it like this - if an entity has not come through the exact instance of ISession you are currently using, then it doesn't know it exists. Hence, it treats everything it's never seen as if it were "new."

One option could be to use the ISession.Load(entity); to reload your parent prior to saving.

free-dom