【问题标题】:NHibernate many-to-one relationshipNHibernate 多对一关系
【发布时间】:2012-07-23 12:12:17
【问题描述】:

我们有以下域对象:-

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

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

因此使用 fluent nhibernate automapper 基于此创建的 sql 模式就像 DeviceRecipient 的表将 UserDevice 的主键作为外键,即 UserDevice_Id。

现在,当我们尝试删除 UserDevice 对象时,它会为外键约束提供 sql 异常。我们要做的是:-

  1. 删除 UserDevice 对象,因此在不删除 DeviceRecipient 的情况下删除 UserDevice 行,因为它将在域模型中的其他地方使用。我们只是想在删除 UserDevice 时将 DeviceRecipient 的 UserDevice_Id 列设置为 null。
  2. 我们希望使用流畅的 nhibernate 约定来实现,就像我们使用 Automapping 一样。

任何帮助都将不胜感激。在此先感谢。!

【问题讨论】:

  • 更正:- 这不是一对一的关系..

标签: sql nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping


【解决方案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();
        }
    }
}

编辑:

来自 NHibernate 参考

not-found (可选 - 默认为异常): 指定如何外来 将处理引用缺失行的键: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

【讨论】:

  • 我确实尝试了这两个..但问题仍然存在..我在数据库中检查了外键允许为 NULL。我还需要做其他检查吗?
  • 好的,我会看一下,但是当使用not-found="ignore" 时,SchemaExport/SchemaUpdate 可能不会创建 FK。我会进行更深入的研究..
  • 是...将 FK 的 OnDelete 行为设置为 Set NULL 有效..!
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
相关资源
最近更新 更多