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_Id として UserDevice の主キーを持っているようなものです。

ここで、UserDevice オブジェクトを削除しようとすると、外部キー制約の SQL 例外が発生します。私たちがやりたいことは:-

  1. UserDevice オブジェクトを削除します。したがって、ドメイン モデルの別の場所で使用されるため、DeviceRecipient を削除せずに UserDevice 行を削除します。UserDevice を削除するときに、DeviceRecipient の UserDevice_Id 列に null を設定したいだけです。
  2. Automapping を使用するため、流暢な nhibernate 規則を使用して実行したいと考えています。

どんな助けでもかなり.. 事前に感謝.!

4

1 に答える 1

1

As I can see you have uni-direction many-to-one relation. So firstly you have to write following override:

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

Secondly you could convert it to automapping convention, if you have more places with this behavior.

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:

From the NHibernate reference

not-found (optional - defaults to exception): Specifies how foreign keys that reference missing rows will be handled: ignore will treat a missing row as a null association.

So when you set not-found="ignore" SchemaExport/SchemaUpdate will just not create the FK for you. So if you have the FK then you need to delete it or set OnDelete behavior of the FK to Set Null. Assuming that you are using Microsoft Sql Server:

ALTER TABLE [DeviceRecipient] 
    ADD CONSTRAINT [FK_DeviceRecipient_LastAttemptedDevice] 
    FOREIGN KEY ([LastAttemptedDevice_ID]) 
    REFERENCES [UserDevice]
    ON DELETE SET NULL
于 2012-07-23T15:32:07.080 に答える