我是Fluent nHibernate的新手,想知道,如果我有两个类Profile和Email映射一对多如下...我想流利地定义一个nHibernate映射,所以当删除Profile时,Email会保留在数据库中,键设置为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);
}
}
答案 0 :(得分:7)
您将无法在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”不是可用的级联行为之一。
在这种情况下,您可以做的最好的事情就是不要级联,而是将关系定义为“反向”(电子邮件“控制”它们属于哪个配置文件;配置文件不“拥有”它们的E-邮件(如此),并在您的存储库中实现逻辑或附加到NHibernate会话,该会话将删除子电子邮件的所有引用到其父配置文件,然后在删除配置文件之前将所有子节点保存为“孤立”记录。