Soft Deletes with EF Core

Introduction

In modern application development, data integrity and recovery are critical considerations. While hard deletes permanently remove data from the database, soft deletes offer a more flexible approach, allowing for data to be "deleted" without being permanently erased. This article will guide you through implementing soft deletes in Entity Framework Core (EF Core), enhancing your application's data management capabilities.

What are Soft Deletes?

Soft deletes mark records as deleted without physically removing them from the database. Instead of deleting the record, a flag (often a boolean or timestamp) is set, indicating that the record is no longer active. This approach preserves historical data and can restore deleted records if needed.

Benefits of Soft Deletes

  • Data Recovery: Accidentally deleted data can be easily restored.
  • Auditability: Historical data is retained, facilitating auditing and compliance.
  • Logical Deletion: Soft deletes support business logic that requires records to be marked inactive without losing historical context.

Implementing Soft Deletes in EF Core

Let's walk through the steps to implement soft deletes in an EF Core application.

1. Define the Soft Delete Flag

First, add a property to your entity model to represent the soft delete flag. This could be a boolean, but a DateTime? property is often more informative.

public class EntityBase
{
    public int Id { get; set; }
    public DateTime? DeletedAt { get; set; }
}

2. Update Your DbContext

Override the OnModelCreating method in your DbContext to automatically apply a global filter for soft deletes. This ensures that all queries exclude soft-deleted records by default.

public class ApplicationDbContext : DbContext
{
    public DbSet<YourEntity> YourEntities { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<YourEntity>().HasQueryFilter(e => e.DeletedAt == null);
    }
}

3. Soft Delete Operation

Create a method to perform the soft delete operation, setting the DeletedAt property instead of removing the record.

public class YourService
{
    private readonly ApplicationDbContext _context;

    public YourService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task SoftDeleteAsync(int id)
    {
        var entity = await _context.YourEntities.FindAsync(id);
        if (entity != null)
        {
            entity.DeletedAt = DateTime.UtcNow;
            await _context.SaveChangesAsync();
        }
    }
}

4. Restoring Soft Deleted Records

To restore a soft-deleted record, set the DeletedAt property to null.

public async Task RestoreAsync(int id)
{
    var entity = await _context.YourEntities
        .IgnoreQueryFilters()
        .FirstOrDefaultAsync(e => e.Id == id);

    if (entity != null)
    {
        entity.DeletedAt = null;
        await _context.SaveChangesAsync();
    }
}

5. Querying Including Soft Deleted Records

Sometimes, you may need to include soft-deleted records in your queries. Use the IgnoreQueryFilters method to bypass the global filter.

public async Task<List<YourEntity>> GetAllIncludingSoftDeletedAsync()
{
    return await _context.YourEntities
        .IgnoreQueryFilters()
        .ToListAsync();
}

Handling Soft Deletes in Your Application

Implementing soft deletes impacts how you handle data operations in your application. Here are some best practices:

  1. Consistent Use of Filters: Always use global query filters to exclude soft-deleted records unless explicitly required otherwise.
  2. UI Indicators: Indicate soft-deleted records in your application's UI, if they are included in any lists or reports.
  3. Data Archiving: Consider implementing archiving policies for long-term storage of soft-deleted records.

Conclusion

Soft deletes provide a robust mechanism for managing data deletions in EF Core applications. You can enhance data recovery, maintain historical records, and improve overall data management by implementing soft deletes. The flexibility of EF Core makes it straightforward to integrate soft deletes into your existing data models, ensuring your application's data integrity and auditability.

By following the steps outlined in this article, you can master soft deletes in EF Core and leverage their benefits to build more resilient and maintainable applications.