Tags: , , | Categories: NHibernate Posted by Admin on 5/30/2011 12:49 PM | Comments (3)

Sometimes people just want to make sure that data isn't ever lost and this usually results in logical or virtual or soft database deletions using a flag IsDeleted. Invariably this is required across the full domain model and to keep things DRY is better implemented within the data access layer.

NHibernate allows us to intercept events with our own code (as all good frameworks should) and the Delete event seems like a good place to go.

public class LogicalDeleteEventListener : DefaultDeleteEventListener
{
    protected override void DeleteEntity(
        NHibernate.Event.IEventSource session, 
        object entity, 
        NHibernate.Engine.EntityEntry entityEntry, 
        bool isCascadeDeleteEnabled, 
        NHibernate.Persister.Entity.IEntityPersister persister, 
        Iesi.Collections.ISet transientEntities)
    {
        if (entity is IBusinessBase)
        {
            ((IBusinessBase)entity).IsDeleted = true;
            ((IBusinessBase)entity).Updated = DateTime.Now;
            CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities);
            CascadeAfterDelete(session, persister, entity, transientEntities);
        }
        else
        {
            base.DeleteEntity(
                session, 
                entity, 
                entityEntry, 
                isCascadeDeleteEnabled, 
                persister, 
                transientEntities);
        }
    }
}

Then just apply this handler to your NHibernate config

config.SetListener(ListenerType.Delete, new LogicalDeleteEventListener());

And now anything implementing IBusinessBase will be logically deleted i.e. IsDeleted == true. Obviously (in this implementation) IBusinessBase needs to have both IsDeleted and Updated properties.

Comments (3) -

linux web hosting United States on 5/31/2011 10:01 AM Hi everybody else !!! The blog was totally fantastic! you all do such a fantastic job at such Concepts..., for one appreciate all you do!
dave @ hostgator discounts United States on 7/4/2011 12:26 PM this is very helpful for everyone to develop something better.
website developer on 9/11/2011 12:22 PM Amazing site, certainly bookmark this great blog post. Thanx for using your experience to create and upload helpful stuff like this article. Best

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading