Table of Contents

Soft deletion

DELETE of a soft-deleted object doesn’t remove its row: it marks the object as deleted, and from then on the object is hidden as if it were removed. It can be restored, audited, or purged later. The notes of docs/samples/Recipes are deleted this way.

Two parts:

  1. a global query filter of EF Core hides the deleted objects from every query;
  2. a custom service marks the object instead of removing it.

Hiding the deleted objects

The entity has the flag:

using Magicalizer.Data.Entities.Abstractions;

namespace App.Data.Entities;

public class Note : IEntity<int>
{
  public int Id { get; set; }
  public int NotebookId { get; set; }
  public string? Title { get; set; }
  public string? Text { get; set; }
  public bool IsDeleted { get; set; }
  public virtual Notebook? Notebook { get; set; }
}

And the DbContext hides the flagged ones with a named global query filter (the names are new in EF Core 10, they let a query switch off one filter and keep the others):

modelBuilder.Entity<Note>(etb => {
  etb.HasKey(e => e.Id);

  // The deleted notes are hidden from all the queries, including the included notes of a notebook.
  etb.HasQueryFilter(SoftDeletionFilter, e => !e.IsDeleted);
  etb.ToTable("Notes");
});

The flag isn’t in the model, the DTO, or the filter: the clients don’t see it and can’t ask for the deleted notes.

Why a global query filter and not a query prefilter? The global filter is applied by EF Core to every query of the entity, including the inclusions and the conditions of the related objects, while a prefilter restricts only the queries of its own service. With a prefilter, GET /v1/notebooks/1?include=notes would still return the deleted notes.

Marking instead of removing

The service overrides DeleteAsync:

public override async Task DeleteAsync(int id, CancellationToken cancellationToken = default)
{
  // The note must be available, as it is for getting it (the prefilters and the soft deletion filter apply).
  if (await this.GetByIdAsync(id, cancellationToken: cancellationToken) == null)
    throw new ModelNotFoundException(typeof(Note), [id]);

  // The note is marked as deleted instead of being deleted.
  await this.dbContext.Set<Data.Entities.Note>()
    .Where(n => n.Id == id)
    .ExecuteUpdateAsync(s => s.SetProperty(n => n.IsDeleted, true), cancellationToken);
}

It first gets the note the usual way, so a note that is already deleted, or isn’t available through the prefilters (e.g. it’s another user’s), is 404 Not Found, as for the default deletion. Then ExecuteUpdateAsync sets the flag with one UPDATE, without loading the entity.

The API is unchanged:

DELETE /v1/notes/2
HTTP/1.1 204 No Content
GET /v1/notebooks/1?include=notes
{
  "id": 1,
  "name": "Ideas",
  "notes": [
    { "id": 1, "notebook": null, "title": "Buy milk", "text": null }
  ]
}

A second DELETE /v1/notes/2 is 404 Not Found, and GET /v1/notes/2, PUT, and PATCH of it are too: the global query filter applies to the checks of the service as well.

Restoring and purging

Your own code reaches the deleted objects by switching off the filter by its name, e.g. in a method of the service:

public async Task RestoreAsync(int id, CancellationToken cancellationToken = default)
{
  await this.dbContext.Set<Data.Entities.Note>()
    .IgnoreQueryFilters([AppDbContext.SoftDeletionFilter])
    .Where(n => n.Id == id && n.IsDeleted)
    .ExecuteUpdateAsync(s => s.SetProperty(n => n.IsDeleted, false), cancellationToken);
}

The other filters (e.g. the owner of a multi-tenant application) stay in force. A background job purges the old deleted rows the same way, with ExecuteDeleteAsync.

Things to keep in mind

  • The deleted rows are still in the table: the unique indexes and the foreign keys see them. E.g. a unique name can’t be reused while the deleted object with it exists, and deleting a notebook removes its notes, the deleted ones included (the relationship is required, so EF Core cascades the deletion).
  • If some users (e.g. the administrators) must see the deleted objects, a prefilter that depends on the user may fit better than a global filter, as in Query prefilters, with its limits on the related objects.
  • Index the flag (or use a filtered index) if the table is large and the deleted rows are many.

See also