如何在Fluent NHibernate中设置"cascade delete"选项以"Set Null"?



我是新来的Fluent nHibernate,想知道,如果我有两个类配置文件和电子邮件映射一对多如下…我想定义一个nHibernate映射流畅,所以当配置文件被删除时,电子邮件将留在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中自动指定此行为。尽管对于NHibernate支持的所有数据库来说,ON DELETE/ON UPDATE行为规范是通用的,但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会话中实现逻辑,将删除所有子电子邮件对其父配置文件的引用,然后在删除配置文件之前将所有子电子邮件保存为"孤儿"记录。

相关内容

最新更新