2011-12-01 62 views
5

我是新來的流利nHibernate,並想知道,如果我有兩個類配置文件和電子郵件映射一對多如下...我想定義一個nHibernate映射流利,所以當配置文件被刪除,電子郵件將保持在數據庫中,鍵設置爲Null。換句話說,要有「ON刪除設置NULL」如何在Fluent NHibernate中將「cascade 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); 
     } 
    } 

回答

7

您將無法在Fluent NHibernate AFAIK中自動指定此行爲。雖然ON DELETE/ON UPDATE行爲規範是常見到NHibernate的支持,NH/FNH控制與級聯行爲的特定級別的級聯所有DBS:

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電子郵件等),並在您的Repository中實施邏輯或附加到NHibernate會話,這將刪除所有子電子郵件引用到他們的父級配置文件,然後在刪除配置文件之前將所有子級保存爲「孤立」記錄。

+0

那是我的想法..非常感謝! –