public interface ISoftDeletable
{
DateTime? DateDelete { set; get; }
}
2. Next, we should create the SoftDeleteEventListener class that inherit from NHibernate.Event.Default.DefaultDeleteEventListener, and simply override the DeleteEntity method.
public class SoftDeleteEventListener : DefaultDeleteEventListener
{
protected override void DeleteEntity(IEventSource session, object entity,
EntityEntry entityEntry, bool isCascadeDeleteEnabled,
IEntityPersister persister, ISet transientEntities)
{
if (entity is ISoftDeletable)
{
var e = (ISoftDeletable)entity;
e.DateDelete = DateTime.Now;
//CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities);
//CascadeAfterDelete(session, persister, entity, transientEntities);
}
else
{
base.DeleteEntity(session, entity, entityEntry, isCascadeDeleteEnabled,
persister, transientEntities);
}
}
}
3. Finally, we need to configure the listener with nhibernate :
Nhibernate.cfg.Configuration configuration = new Configuration().Configure();
configuration.SetListener(ListenerType.Delete, new SoftDeleteEventListener());
configuration.BuildSessionFactory();
4. Now, to hide a deleted data, we define a soft delete filter in mapping file for which we need to keep a permanent record :
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ...>
<class ...>
…
<property name="DateDelete" column="DateDelete" type="DateTime" />
<filter name="SoftDeleteFilter"> </filter>
</class>
<filter-def name="SoftDeleteFilter" condition="DateDelete IS NULL">
</filter-def>
</hibernate-mapping>
5. and, in the application_beginrequest, you should enable soft delete filter on the nhibernate session :
nhibernateSession.EnableFilter(“SoftDeleteFilter”).Validate();
No comments:
Post a Comment