Nhibernate - 使用Cascade all-delete-orphan进行一对一映射,而不是删除孤儿

时间:2011-04-18 15:11:07

标签: c# nhibernate domain-driven-design nhibernate-mapping ddd-repositories

我有一个'面试'实体,它与'FormSubmission'实体有一对一的映射,面试实体是占优势的一面,可以这么说,映射是:

<class name="Interview">
    <id name="Id" column="Id" type="Int64">
        <generator class="identity" />
    </id>

    // other props (snip)....

    <one-to-one name="Submission" class="FormSubmission"
        cascade="all-delete-orphan" />
</class>

<class name="FormSubmission">
    <id name="Id" column="Id" type="Int64">
        <generator class="foreign">
            <param name="property">Interview</param>
        </generator>
    </id>

    // other props (snip)....

    <one-to-one name="Interview" class="Interview"
        constrained="true" cascade="none" />
</class>

两个实体都是聚合的一部分,采访充当聚合根。我正在尝试通过Interview实体保存/更新/删除FormSubmission,因此我将关联的Interview结束映射为cascade =“all-delete-orphan”。例如,我可以像这样创建一个新的FormSubmission:

myInterview.Submission = new FormSubmission(myInterview);
InterviewRepository.Save(myInterview);

...这很好用,FormSubmission已保存。但是,我似乎无法删除我试图这样做的FormSubmission:

myInterview.Submission = null;
InterviewRepository.Save(myInterview);

...但这似乎没有删除FormSubmission。我已经尝试将null赋给协会的两边:

myInterview.Submission.Interview = null;
myInterview.Submission = null;
InterviewRepository.Save(myInterview);

我甚至尝试在FormSubmission端设置cascade =“all-delete-orphan”,但似乎没有任何效果。我错过了什么?

1 个答案:

答案 0 :(得分:5)

可能这不是你想要的答案。根据此问题,主键一对一关联不支持“All-delete-orphan”级联:https://nhibernate.jira.com/browse/NH-1262。即使是外键一对一关联也很可能忽略“all-delete-orphan”级联:

<class name="Interview">
    <id name="Id" column="Id" type="Int64">
        <generator class="identity" />
    </id>

    <property name="Name" />

    <many-to-one name="Submission" unique="true" cascade="all-delete-orphan" />
</class>

<class name="FormSubmission">
    <id name="Id" column="Id" type="Int64">
        <generator class="identity" />
    </id>

    <property name="Name" />

    <one-to-one name="Interview" cascade="all-delete-orphan" property-ref="Submission"  />
</class>

编辑: jchapman suggests使用拦截器(事件监听器在NH2.x及更高版本中更受欢迎)来模仿这个听起来很有趣的功能,但我还不知道如何实现这样的拦截器/事件监听器。