简体   繁体   中英

Soft delete - ActiveRecord with Listeners

I am using ActiveRecord with nHibernate and am trying to implement a soft delete so objects are marked as "IsDeleted" rather than actually deleting them. I obviously need the cascade option to work.

[assembly: AddEventListener(typeof(MyNamespace.SoftDeleteListener))] namespace MyNamespace { public class SoftDeleteListener : DefaultDeleteEventListener
{
    protected override void DeleteEntity(IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled,
        IEntityPersister persister, ISet transientEntities)
    {
        if (entity is IPermanentRecord)
        {
            ((IPermanentRecord)entity).IsDeleted = true;
            this.CascadeBeforeDelete(session, persister, entity,
                entityEntry, transientEntities);
            this.CascadeAfterDelete(session, persister, entity, transientEntities);
        }
        else
        {
            base.DeleteEntity(session, entity, entityEntry,
                isCascadeDeleteEnabled, persister, transientEntities);
        }
    }
}

}

My entity - "Product" Implements

interface IPermanentRecord
{
    bool IsDeleted { get; set; }
}

The problem is, the listener doesn't get fired when deleting the entity it just deletes it!

To anyone that is interested...

I found the nHibernate configuration and added the listener manually and it fired..

foreach (NHibernate.Cfg.Configuration cfg in ActiveRecordMediator.GetSessionFactoryHolder().GetAllConfigurations())
        {
            cfg.SetListener(ListenerType.Delete, new SoftDeleteListener());
            cfg.AddAssembly(assem);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM