1

我們有以下的域對象: -NHibernate的許多一對一的關係

public class UserDevice : BaseObject 
{ 
// different properties to hold data 
} 

public class DeviceRecipient:BaseObject 
{ 
public virtual UserDevice LastAttemptedDevice{get;set;} 
} 

因此,在此基礎上用流利的NHibernate automapper創建的SQL模式是像 DeviceRecipient的表是有UserDevice的主鍵作爲外鍵即UserDevice_Id。

現在,當我們嘗試刪除UserDevice對象時,它會爲外鍵約束提供一個sql異常。我們想要做的是: -

  1. 刪除UserDevice對象,因此UserDevice行不刪除DeviceRecipient,因爲它將在域模型中的其他位置使用。我們只是想在刪除UserDevice時將DeviceRecipient的UserDevice_Id列設置爲null。
  2. 我們想使用流利的nhibernate約定來做到這一點,因爲我們使用Automapping。

任何幫助將明顯..在此先感謝。

+0

更正: - 這不是一個一對一的關係.. – Niraj 2012-07-23 12:24:33

回答

1

正如我所見,你有單向多對一的關係。所以首先你必須寫下面的覆蓋:

public class DeviceRecipientOverride : IAutoMappingOverride<DeviceRecipient> 
{ 
    public void Override(AutoMapping<DeviceRecipient> mapping) 
    { 
     mapping.References(x => x.LastAttemptedDevice) 
      .NotFound.Ignore(); // this doing what you want. 
    } 
} 

其次你可以將它轉換爲automapping約定,如果你有更多的地方這種行爲。

public class ManyToOneNullableConvention : IReferenceConvention 
{ 
    public void Apply(IManyToOneInstance instance) 
    { 
     var inspector = (IManyToOneInspector) instance; 
     // also there you could check the name of the reference like following: 
     // inspector.Name == LastAttemptedDevice 
     if (inspector.Nullable) 
     { 
      instance.NotFound.Ignore(); 
     } 
    } 
} 

編輯

從NHibernate的參考

未找到(可選 - 默認爲exception):指定引用缺失行的外國 鍵將如何處理:ignore會將 缺失的行視爲空關聯。

因此,當您設置not-found="ignore" SchemaExport/SchemaUpdate將不會爲您創建FK。因此,如果您有FK,那麼您需要將其刪除或將FK的OnDelete行爲設置爲Set Null。假設你使用Microsoft SQL Server:

ALTER TABLE [DeviceRecipient] 
    ADD CONSTRAINT [FK_DeviceRecipient_LastAttemptedDevice] 
    FOREIGN KEY ([LastAttemptedDevice_ID]) 
    REFERENCES [UserDevice] 
    ON DELETE SET NULL 
+0

我曾嘗試他們both..but問題仍然存在。我在數據庫中檢查外鍵允許NULL。我需要做的其他支票? – Niraj 2012-07-24 09:03:43

+0

好吧,我會看看,但是當'not-found =「ignore」'被使用時,那麼SchemaExport/SchemaUpdate就不會創建FK。我會採取更深入的外觀.. – hazzik 2012-07-24 10:10:13

+0

是的...設置FK的OnDelete行爲設置NULL工作..! – Niraj 2012-07-25 12:09:53