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