2011-05-06 81 views
5

我有两个类。一个称为Employee,另一个称为EmployeeDetails,与其父类'Employee'有零或一个关系。换句话说,有些时候我们需要将额外的数据存储到这个'EmployeeDetails'类中,但这不一定是标准。数据库结构非常简单,'EmployeeDetails'与其父级共享相同的ID。nHibernate,一对零或一个关系woes

我得到的问题是从'Employee'类中删除'EmployeeDetails'类,我会想象将对象设置为null会完成技巧和刷新会话,但DB中的记录不会被删除。

我的映射是...

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> 
    <class name="StudioBusinessLayer.Data.Structure.Employee, StudioBusinessLayer" table="tblEmployee" lazy="false"> 
     <id name="ID" column="ID" type="int"> 
      <generator class="native" /> 
     </id> 

     <property name="Name" column="Name" not-null="true" type="string" length="100" /> 
     <!-- etc --> 

     <one-to-one constrained="false" name="EmployeeDetails" class="StudioBusinessLayer.Data.Structure.EmployeeDetails, StudioBusinessLayer" cascade="all-delete-orphan" /> 

    </class> 
</hibernate-mapping> 

...并为EmployeeDetails类...

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> 
    <class name="StudioBusinessLayer.Data.Structure.EmployeeDetails, StudioBusinessLayer" table="tblDetails" lazy="false"> 
     <id name="ID" column="DetailsID" type="int"> 
      <generator class="foreign"> 
       <param name="property">Employee</param> 
      </generator> 
     </id> 

     <property name="Address" column="Address" not-null="false" type="string" length="1000" /> 
     <property name="ContactEmail" column="ContactEmail" not-null="false" type="string" length="255" /> 
     <property name="ContactName" column="ContactName" not-null="false" type="string" length="255" /> 
     <property name="ContactTelephone" column="ContactTelephone" not-null="false" type="string" length="255" /> 
     <property name="ZipCode" column="ZipCode" not-null="true" type="string" length="100" /> 

     <many-to-one name="Employee" class="StudioBusinessLayer.Data.Structure.Employee, StudioBusinessLayer" column="DetailsID" insert="false" update="false"></many-to-one> 

    </class> 
</hibernate-mapping> 

插入和更新工作正常,但我一直在努力寻找开关,使这项工作删除。

任何帮助或建议感激地收到...

回答

2

不幸的是,在NHibernate中,一对一关系不支持all-delete-orphan。有关更多详细信息,请参阅此issue或此SO question。似乎没有其他办法可以通过您自己的方式删除EmployeeDetails,也可以使用一个事件侦听器来模拟一对一的all-delete-orphan。

+0

不用担心,幸好这个东西可以被业务层处理,所以虽然nHibernate的实现并不是很好,至少它的封装了。干杯 – SeanCocteau 2011-05-09 09:08:07

0

EmployeeDetails映射看起来不正确。看起来像Employee的多对一​​映射也应该是一对一的,但我没有看到tblDetails有一个Employee.Id值的列。没有它,你不能建立NHibernate的删除逻辑的双向关联,以知道哪个tblDetails行属于哪个Employee。

UPDATE:

我找到了如何在一到一个关系映射good sample但它是严格一到一个场景。它确实提到需要检查子表以确定是否存在关联,以便在此处适用,但可能需要在代码中进行一些手动检查。