如何在 Fluent NHibernate 中将“级联删除”选项设置为“设置空”?

2024-03-24

我是 Fluent nHibernate 的新手,想知道,如果我有两个类 Profile 和 Email 一对多映射,如下所示...我想流畅地定义一个 nHibernate 映射,这样当 Profile 被删除时,Email 将保留在DB,键设置为 Null。或者换句话说,“ON DELETE SET NULL”

ALTER TABLE [dbo].[Email]  WITH CHECK ADD  CONSTRAINT [FK4239B252F6539048] FOREIGN KEY([ProfileId])
REFERENCES [dbo].[Profile] ([Id])
ON UPDATE SET NULL
ON DELETE SET NULL

任何帮助是极大的赞赏!

public sealed class ProfileMapping : ClassMap<Profile>
        {
            public ProfileMapping()
            { 
                // Some other fields here ...
                HasMany(x => x.Emails);
            }
        }

    public class EmailMapping : ClassMap<Email>
    {
        public EmailMapping()
        {
            Id(x => x.Id).GeneratedBy.GuidComb();
            Map(x => x.Address).Not.Nullable().UniqueKey("UX_EmailAddress").Length(254);
            Map(x => x.Confirmed);
        }
    }

您将无法在 Fluent NHibernate AFAIK 中自动指定此行为。尽管 ON DELETE/ON UPDATE 行为规范对于 NHibernate 支持的所有 DB 都是通用的,但 NH/FNH 通过特定级别的级联行为控制级联:

none - do not do any cascades, let the users handles them by themselves.
save-update - when the object is saved/updated, check the assoications and save/update any object that require it (including save/update the assoications in many-to-many scenario).
delete - when the object is deleted, delete all the objects in the assoication.
delete-orphan - when the object is deleted, delete all the objects in the assoication. In addition to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.
all - when an object is save/update/delete, check the assoications and save/update/delete all the objects found.
all-delete-orphan - when an object is save/update/delete, check the assoications and save/update/delete all the objects found. In additional to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.

正如您所看到的,“SET NULL”不是可用的级联行为之一。

在这种情况下,您能做的最好的事情就是根本不级联,而是将关系定义为“反向”(电子邮件“控制”它们所属的配置文件;配置文件本身并不“拥有”其电子邮件),并在您的存储库中或附加到 NHibernate 会话中实现逻辑,该逻辑将删除子电子邮件对其父配置文件的所有引用,然后在删除配置文件之前将所有子项保存为“孤立”记录。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Fluent NHibernate 中将“级联删除”选项设置为“设置空”? 的相关文章

随机推荐