0

我目前正在研究一個小型PoC項目,並決定採取NHibernate作爲持久性部分的自旋。NHibernate在關聯的連接子類中級聯刪除

我已經定義了下列域的實體:

  • 位置抽象類表示位置(位置樹的根)
  • FixedLocation抽象類表示地理固定位置(源自位置)
  • 國家:代表一個國家(從位置派生)
  • :代表一個國家內的城市(從位置派生,並不能在邏輯上存在沒有國家)

要求:

  1. 所有位置必須最終從位置派生(相關地,所有位置後代將共享相同範圍的數據庫密鑰)
  2. A 雙向關係應該存在t在國家和城市之間
  3. 刪除應該在整個實體樹中級聯,例如,刪除國家也應刪除相關城市

下面是如何映射上述類

<?xml version="1.0" encoding="utf-8" ?> 
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="AET.PoC.Domain" namespace="AET.PoC.Domain.Entities">  
    <class name="Location" table="Locations" abstract="true"> 
     <id name="Id" type="Int64" unsaved-value="0"> 
     <generator class="native" /> 
     </id> 
     <property name="LocationType" access="readonly" /> 
    </class> 
    <joined-subclass name="FixedLocation" table="FixedLocations" extends="Location" abstract="true"> 
     <key column="LocationId" /> 
     <component name="GPSPosition" class="GPSPosition"> 
      <property name="Latitude" type="double" /> 
      <property name="Longitude" type="double" /> 
     </component> 
    </joined-subclass> 
<joined-subclass name="Country" table="Countries" extends="FixedLocation"> 
    <key column="FixedLocationId" /> 
    <property name="Name" length="50" not-null="true" /> 
<set name="CitySet" cascade="all, delete-orphan" inverse="true"> 
    <key column="CountryId" foreign-key="FK_City_Country" on-delete="cascade" /> 
    <one-to-many class="City" /> 
    </set> 
    </joined-subclass> 
<joined-subclass name="City" table="Cities" extends="FixedLocation"> 
    <key column="FixedLocationId" /> 
    <many-to-one name="Country" class="Country" column="CountryId" not-null="true" cascade="all, delete-orphan" /> 
    <property name="Name" length="50" not-null="true" /> 
    </joined-subclass> 
    </hibernate-mapping> 

這些類映射這樣fullfils上述要求,或至少部分......

當我刪除()一個國家實體(說地點ID 1),有2個相關的城市對象(說地點ID 2和3),這是發生了什麼事情:

  1. FixedLocationId = 1的記錄從國家表中刪除
  2. 這些記錄與FixedLocationId = 2和3從城市表中刪除
  3. LocationId = 1從刪除的記錄所述FixedLocations表
  4. = 1從位置表中刪除與ID的記錄

到目前爲止,這麼好,但...

  • 這些記錄與LocationId = 2和3從FixedLocations表中刪除
  • 的與ID = 2和3的記錄刪除從地點表
  • 我在這裏做錯了什麼?這可以在第一時間完成嗎?

    我試圖在標籤的設置上刪除=「級聯」屬性,而是由NHibernate抱怨沒有被允許圓形級聯...

    回答

    0

    不要把級聯許多-TO-一個在城市。相反,確保每個位置都知道孩子的位置:

    <class name="Location" table="Locations" abstract="true"> 
        .... 
        <many-to-one name="_parent" column="ParentLocationID" /> 
        .... 
        <set name="_childLocations" table="Locations" inverse="true" cascade="all-delete-orphan" > 
         <key column="ParentLocationID" /> 
         <one-to-many class="Location"/> 
        </set> 
        .... 
    </class> 
    

    這樣,你有你的層次和對象的生命週期的工作,妥善級聯。您可以在子類中採用其他要求。