【发布时间】:2009-02-04 09:54:36
【问题描述】:
当我尝试使用 NHibernate 来持久化 2 个对象的新实例时,这些对象之间有多个关联:
NHibernate.Exceptions.GenericADOException: could not insert: [MyProject.BusinessEntities.Client][SQL: INSERT INTO dbo.Client (Version, CurrentEvent_ClientEvent_Id, EntityType, Id) VALUES (?, ?, 'MyProject.BusinessEntities.Client', ?)] ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK328F067A46E318FD". The conflict occurred in database "DatabaseName", table "dbo.ClientEvent", column 'ClientId'.
场景如下:
我有 2 个类(为清楚起见,我已重命名):Client 和 ClientEvent。 客户端有一个名为 Events 的属性,它的类型为 List。 ClientEvent 包含一个属性“Client”,它是与 Client 对象的反向关联。 此外,Client 类还有另一个名为 CurrentEvent 的属性,其中包含对 ClientEvents 集合中的一项的引用。
Client.hbm.xml 包含:
<bag name="ClientEvents" access="field.camelcase-underscore" inverse="true" cascade="save-update">
<key column="Client_Id"/>
<one-to-many class="MyProject.BusinessEntities.ClientEvent, MyProject.BusinessEntities" />
</bag>
<many-to-one name="CurrentEvent" access="property" class="MyProject.BusinessEntities.ClientEvent, MyProject.BusinessEntities" column="CurrentEvent_ClientEvent_Id" cascade="save-update" />
ClientStatusRecord.hbm.xml 包含:
<many-to-one name="Client" access="property" class="MyProject.BusinessEntities.Client, MyProject.BusinessEntities" column="Client_Id" cascade="save-update" />
我从映射中自动生成数据库架构,并且两个表中的外键都可以为空。
我使用下面的代码来持久化一个新的Client和ClientRecord(再次简化以删除所有的会话管理gumpf)
var newClient = CreateNewClient();
var newEvent = CreateNewEvent();
newEvent.client = newClient; // ensure the reverse association is set
newClient.Events.Add(newEvent);
session.SaveOrUpdate(newClient);
session.Flush();
查看 NHibernate 的 SQL 输出,它似乎在保存 ClientEvent 记录之前尝试保存 Client 记录,尝试将 ClientEvent Id 插入外键,但由于 ClientEvent 记录尚不存在而失败
问题
- 有没有人让它在 nhibernate 持久化具有多个关系的对象时工作?
- 如果是这样,映射应该是什么样的?
- 有什么我可以尝试的建议吗?
很抱歉这篇冗长的帖子
【问题讨论】:
标签: nhibernate