Soft Delete is a persistence pattern where instead of removing entities physically you just mark them as deleted by setting a fixed value in one of columns.
For example, in XPO (DevExpress Persistence Objects) an additional int column called GCRecord holds a null value (not deleted) or anything than null (deleted).
There’s a long discussion whether or not such approach is a pattern or an antipattern but this is beyond this post. What I would like to show is how to get soft deletes with NHibernate so that you can migrate your XPO application to NHibernate and keep your database untouched.
Filtering the data
There are two issues to solve. First – NHibernate should automatically append “filters” so that all queries will select only the data which is not deleted. I’ve blogged on this few months ago. An example code which sets filters for XPO-compatible database is:
and then you just enable filters:
Because of filters, NHibernate will append the “GCRecrod is null” to queries and subqueries thus simulating the way XPO filters the data.
Note that NHibernate’s feature of filtering is way, way more advanced – you are free to define any filter you need while XPO has one builtin filter which cannot be easily changed (can it be changed at all?).
Persisting the data
The remaining task is to teach NHibernate to mark records as deleted when it comes to deleting data. This is done with an event listener:
which is applied by:
Audit logging the data
Event listeners can be used not only to soft delete the data. Suppose for example that your entity holds a simple auditing info (insert date, modify date):
You can set up an event lister to automatically set values to the two columns:
and apply listeners:
Putting all this toghether, it is possible to migrate your XPO persistence layer to NHibernate without losing the Soft Delete feature.