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.
30b1adbe-284c-499c-ac0e-beb6dc8ea720|0|.0