Inheritance 关联联接子类中的NHibernate级联删除
我目前正在从事一个小的PoC项目,并决定为持久性部分做一番尝试 我已定义了以下域实体: 位置:表示位置树的位置根的抽象类 FixedLocation:表示地理位置固定的抽象类派生自location 国家:表示从位置派生的国家 城市:表示一个国家/地区内的一个城市,该城市源于位置,并且在没有国家/地区的情况下在逻辑上无法存在 要求: 所有位置最终都必须从位置关系派生,所有位置子体将共享相同范围的数据库键 农村和城市之间应该存在双向关系 删除应在整个实体树中级联,例如,删除国家/地区也应删除关联的城市 下面是我如何映射上述类的Inheritance 关联联接子类中的NHibernate级联删除,inheritance,nhibernate,cascade,cascading-deletes,joined-subclass,Inheritance,Nhibernate,Cascade,Cascading Deletes,Joined Subclass,我目前正在从事一个小的PoC项目,并决定为持久性部分做一番尝试 我已定义了以下域实体: 位置:表示位置树的位置根的抽象类 FixedLocation:表示地理位置固定的抽象类派生自location 国家:表示从位置派生的国家 城市:表示一个国家/地区内的一个城市,该城市源于位置,并且在没有国家/地区的情况下在逻辑上无法存在 要求: 所有位置最终都必须从位置关系派生,所有位置子体将共享相同范围的数据库键 农村和城市之间应该存在双向关系 删除应在整个实体树中级联,例如,删除国家/地区也应删除关联的城
<?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>
以这种方式映射这些类满足了上述要求,或者至少部分满足了
当我删除一个国家实体(如location ID 1)时,它有两个关联的城市对象(如location ID 2和3),会发生以下情况:
将从国家/地区表中删除FixedLocationId=1的记录
FixedLocationId=2和3的记录将从Cities表中删除
LocationId=1的记录将从FixedLocations表中删除
Id=1的记录将从位置表中删除
到目前为止还不错,但是
LocationId=2和3的记录不会从FixedLocations表中删除
Id为2和3的记录不会从位置表中删除
我做错了什么?这首先能做到吗
我试着在标签中设置on delete=cascade属性,但这让我抱怨不允许循环级联…不要在城市中的多对一上放置级联。相反,请确保每个位置都知道子位置:
<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>
这样,您的层次结构和对象生命周期就可以正常工作和级联。您可以在子类中考虑其他需求