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.
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.
So, in the mapping file, the association looks e.g. like this:
<bag name="DateTimes" table="FreightDateTimes" lazy="false" cascade="all">
<key column="ConsignmentId"/>
<many-to-many class="Logistics.FreightDateTime, Logistics" column="DateTimeId" />
</bag>
Setting cascade to "all" yields:
System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'DateTimeId', table 'LogiGate.dbo.FreightDateTimes'; column does not allow nulls. INSERT fails.
Setting cascade to "none" yields:
NHibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Logistics.FreightDateTime
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.
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.