簡體   English   中英

NHibernate - Cascade Merge到子實體對於分離的父實體失敗

[英]NHibernate - Cascade Merge to child entities fails for detached parent entity

目前的方法

在ASP.NET Web表單應用程序(使用Spring.NET和NHibernate)中,我們有一個聚合根( Person ),其詳細信息可以在多個屏幕/頁面中捕獲。 Person實體在進入此工作流之前存在,並且對Person對象圖所做的所有更改都是原子的,因此只應在提交最終屏幕時刷新到數據庫。

為了實現這一點,我們首次使用NHibernate 3.2將數據庫中的Person (懶惰)加載到第一頁,然后在我們瀏覽過程時加載並將序列化的Person對象圖保存到HTTP Session變量中。

從HTTP會話中檢索Person后,它與當前NHibernate會話處於分離狀態,因此我們通過在當前會話上調用Update()方法重新附加,如下所示:

var sessionPerson = Session[PersonSessionName] as Person;
var currentSession = SessionFactory.GetCurrentSession();
currentSession.Update(sessionPerson);

注意:使用Lock()引發異常,建議“重新關聯的對象有臟集”。

重新連接時,我們可以按預期遍歷對象圖,從數據庫中提取尚未加載到內存中的子實體的數據。

映射文件的子集

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="false" assembly="Domain" namespace=" TestApp.Domain">
  <class name="Person" table="Person">
    <id name="Id">
      <generator class="TestApp.CustomNHibernateHiLoGenerator, TestApp.Core" />
    </id>
    <property name="Name" not-null="false" />

    <bag name="PersonCountries" access="field.camelcase-underscore" cascade="all-delete-orphan">
      <key column="PersonId" foreign-key="FK_ PersonCountry_Person" not-null="true" />
      <one-to-many class="PersonCountry" />
    </bag>
  </class>

  <class name="Country" table="Country">
    <id name="Id">
      <generator class="TestApp.CustomNHibernateHiLoGenerator, TestApp.Core" />
    </id>
    ... No back reference to Person
  </class>
</hibernate-mapping>

public class PersonCountry : Entity, ICloneable
{
    // No properties of note
}

public class Person : Entity, ICloneable
{
    public virtual string Name { get; set; }
    public virtual IEnumerable<PersonCountry> PersonCountries { get; set; }
    ... 
    // More Properties
}

刷新對數據庫的更改

.. // Code-behind
PricingService.Save(ProductContext.Pricing, forceMerge: true);            


public class PricingService : IPricingService
{
   [Transaction]  // Spring.NET transaction
   public Pricing Save(Pricing pricing, bool forceMerge = false)
   {            
      if(forceMerge)
      {
         CurrentSession.Merge(entity);
      }
      else
      {
         CurrentSession.SaveOrUpdate(entity);
      }
   }
}

當需要刷新對數據庫的所有更改時,如果我們只更改Name ,則更改將按預期工作。 但是,向Person添加新的Country項會導致一對多關系上Merge()的級聯失敗,並出現以下異常(奇怪的是,刪除Country可以正常工作)。

NHibernate.StaleStateException: Batch update returned unexpected row count from update; actual row count: 0; Expected: 1

任何幫助將不勝感激。

具有有效Id的每個實體都被視為持久性,這就是為什么它嘗試在合並中更新它但是因為它尚未保存但它失敗了。 session.Flush()之后調用session.Update()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM