title: NHibernate: many-to-many relation fails to save child objects first (either: "cannot insert null" or: "transient object")
body: <p>I have a consignment class that aggregates a FreightDateTime class. At the same time, the FreightDateTime class is  also aggregated by the GoodsItem class. In the same manner, FreightDateTime is associated with a number of other classes that I left out for now. </p>
  
  <p>To avoid a databasetable FreightDateTime with ConsignmentId foreign key, a GoodsItemId foreign key, etc. I decided that the association should be many-to-many. This way, NHibernate would generate an association table for each relationship instead (ConsigmentFreightDateTimes, GoodsItemFreightDateTimes), which makes more sense. </p>
  
  <p>So, in the mapping file, the association looks e.g. like this: </p>
  
  <pre><code>&lt;bag name="DateTimes" table="FreightDateTimes" lazy="false" cascade="all"&gt;
    &lt;key column="ConsignmentId"/&gt;
    &lt;many-to-many class="Logistics.FreightDateTime, Logistics" column="DateTimeId" /&gt;
  &lt;/bag&gt;
  </code></pre>
  
  <p>Setting cascade to "all" yields: </p>
  
  <pre><code>System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'DateTimeId', table 'LogiGate.dbo.FreightDateTimes'; column does not allow nulls. INSERT fails. 
  </code></pre>
  
  <p>Setting cascade to "none" yields: </p>
  
  <pre><code>NHibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Logistics.FreightDateTime
  </code></pre>
  
  <p>In both cases, this means that NHibernate is trying to save the Consignment instance, although the child FreightDateTime instances have not been saved. In the first case, the foreign key is still 'null', which thus cannot be inserted in the resulting table,  and in the second case, NHibernate is aware that the instance has not yet been saved, and thus throws the exception. </p>
  
  <p>So the question is how I can get NHibernate to save all child instances first without explicitly telling it to do so. I have hunch that allowing nulls on column DateTimeId would do the trick, but I think that is neither desirable nor possible. </p>