我得到試圖使用NHibernate的堅持2個對象之間有多個協會的新實例時,出現以下錯誤: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" />
我自動生成的映射數據庫架構,以及兩個表中的外鍵都是可空的。
我使用下面的代碼堅持一個新的客戶端和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記錄之前保存的客戶記錄,試圖插入ClientEvent標識成失敗外鍵,因爲ClientEvent記錄不存在尚未
問題
- 有沒有人知道nhibernate在多重關係中持續存在對象?
- 如果是這樣,映射應該是什麼樣子?
- 我可以嘗試的任何建議嗎?
對不起,冗長的職位