我有一个聚合 FreightDateTime 类的寄售类。同时,FreightDateTime 类也被 GoodsItem 类聚合。同样,FreightDateTime 与我暂时忽略的许多其他类相关联。
为了避免使用 ConsignmentId 外键、GoodsItemId 外键等的数据库表 FreightDateTime。我决定关联应该是多对多的。这样,NHibernate 将为每个关系生成一个关联表(ConsigmentFreightDateTimes,GoodsItemFreightDateTimes),这更有意义。
因此,在映射文件中,关联看起来像这样:
<bag name="DateTimes" table="FreightDateTimes" lazy="false" cascade="all">
<key column="ConsignmentId"/>
<many-to-many class="Logistics.FreightDateTime, Logistics" column="DateTimeId" />
</bag>
将级联设置为“全部”会产生:
System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'DateTimeId', table 'LogiGate.dbo.FreightDateTimes'; column does not allow nulls. INSERT fails.
将级联设置为“无”产生:
NHibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Logistics.FreightDateTime
在这两种情况下,这意味着 NHibernate 正在尝试保存 Consignment 实例,尽管尚未保存子 FreightDateTime 实例。在第一种情况下,外键仍然是'null',因此不能插入到结果表中,而在第二种情况下,NHibernate 知道该实例尚未保存,因此抛出异常。
所以问题是我怎样才能让 NHibernate 先保存所有子实例而不明确告诉它这样做。我有预感,允许 DateTimeId 列上的空值可以解决问题,但我认为这既不可取也不可能。