【问题标题】:Nhibernate - One-to-one mapping with Cascade all-delete-orphan, not deleting the orphanNhibernate - 与 Cascade all-delete-orphan 的一对一映射,不删除孤儿
【发布时间】:2011-08-07 23:30:26
【问题描述】:

我有一个“Interview”实体,它与“FormSubmission”实体具有一对一的映射关系,可以说,Interview 实体是主要的一面,映射是:

<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",但似乎没有任何效果。我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    这可能不是您想要的答案。根据此问题:https://nhibernate.jira.com/browse/NH-1262,主键一对一关联不支持“All-delete-orphan”级联。即使是外键一对一关联也很可能会忽略“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 及更高版本中更受欢迎)来模拟这个听起来很有趣的功能,但我还不清楚如何实现这样的拦截器/事件监听器。

    【讨论】:

    • 天啊,太糟糕了!我想知道他们不支持它的理由是什么?从 Fabio Maulo 的回应语气来看:“与‘all-delete-orphan’一对一?’我猜他认为这种映射是个坏主意,但我想知道为什么?
    • 很难说,这是直接给法比奥的问题:)。无论如何,根据这个问题opensource.atlassian.com/projects/hibernate/browse/HHH-2608,它似乎已经在Hibernate 3.5(一岁)中实现了。不知道 Hibernate 和 NHibernate 版本是如何相关的......
    • NH-1262 issue 现在在即将发布的 4.1 版本中被标记为已解决。
    • NH-1262 问题确实已修复并在 NHibernate 4.1 中运行。 This 可以帮助你使用流畅的nhibernate。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多