首页 文章

NHibernate多对一的关系

提问于
浏览
1

我们有以下域对象: -

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异常 . 我们想做的是: -

  • 删除UserDevice对象,因此删除UserDecipient而不删除DeviceRecipient,因为它将在域模型中的其他位置使用 . 我们只想在删除UserDevice时将null设置为DeviceRecipient的UserDevice_Id列 .

  • 我们希望使用流畅的nhibernate约定来实现它,因为我们使用Automapping .

任何帮助都会很明显..在此先感谢 . !

1 回答

  • 1

    我可以看到你有单向的多对一关系 . 首先,你必须写下面的覆盖:

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

    其次,如果您有更多具有此行为的地方,您可以将其转换为自动约定 .

    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();
            }
        }
    }
    

    EDIT

    来自NHibernate参考

    not-found(可选 - 默认为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
    

相关问题