Soft Deletion
By default, when you delete an entity through LightSpeed, it is deleted from the database – that is, LightSpeed sends a SQL DELETE statement. However, you can specify that entities of a particular type should be soft deleted – that is, instead of being deleted, they should be left in the database but marked with a ‘deleted’ flag.
To have LightSpeed use soft deletion for an entity type, select the entity and set its Soft Delete option to true.
The Soft Delete option creates a field named DeletedOn. The DeletedOn field is a nullable DateTime, which is null by default, but which LightSpeed automatically populates when the entity is deleted.
The database must contain a corresponding DeletedOn column. If you use Update Database or Create Migration in the designer, it will create this column for you. If you create the column manually, it must be a nullable column of date-time type.
Storing Which User Deleted an Entity
To have LightSpeed automatically store the user who deleted a soft-deleted entity, add a DeletedBy string fields to the entity, and set the LightSpeedContext.AuditInfoMode.
If AuditInfoMode is set, LightSpeed automatically populates the DeletedBy field when the entity is deleted. You should normally mark the field as Load Only so that application code does not try to modify it.
For compatibility reasons, the DeletedBy field is not used for automatic storage by default: you must enable the policy through the AuditInfoMode.
Because different applications identify users in different ways, the user id written into the DeletedBy field depends on the AuditInfoMode. See below for further information.
Obviously, DeletedBy is not meaningful for hard-deleted entities.
Loading Soft Deleted Entities
Soft deleted entities remain in the database after deletion, and can be retrieved using LightSpeed. To include deleted entities in a query, apply the IncludeDeleted operator to the query:
Loading soft deleted entities |
var allOrders = unitOfWork.Orders.IncludeDeleted(); |
(If using query objects, set Query.IncludeDeleted to true.)
IncludeDeleted does not limit the query to deleted entities – it will return both deleted and non‑deleted entities. You can use the DeletedOn field to distinguish deleted entities.
LightSpeed does not provide a way to purge or restore soft deleted entities. These are database administration tasks and should be handled as such.