2009-02-03 30 views
1

我得到試圖使用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在多重關係中持續存在對象?
  • 如果是這樣,映射應該是什麼樣子?
  • 我可以嘗試的任何建議嗎?

對不起,冗長的職位

回答

3

謝謝,我嘗試了在Client和ClientEvent映射中將級聯屬性設置爲Save-Update或None的所有組合,但沒有成功。

但是,通過從頭開始逐步構建我的映射,我找出了問題所在......我在Client和ClientEvent對象上設置Id,而不是讓NHibernate在對象時生成值堅持下去。在大多數情況下,如果您在保留對象之前顯式設置Id,則似乎並不重要。但是,在這種情況下,NHibernate似乎錯誤地解決了對象需要保存的順序,並嘗試保留引用ClientEvent的客戶端記錄不存在。

解決方案:讓NHibernate爲對象生成標識符

0

我想這是一個關於級聯,試圖改變在映射級聯的值。 不是100%肯定,但是,嘗試在很多映射中將級聯設置爲「無」