Skip to content

Triggers and traits (e.g. SoftDelete)

Koen edited this page Nov 29, 2020 · 1 revision

Triggers are not restricted for entity types only but can also be defined for base classes or even interfaces. Consider that we want to implement soft delete using triggers:

public interface ISoftDelete {
    DateTime? DeletedOn { get; set; } 
}

public class EnsureSoftDeletedTrigger : IBeforeSaveTrigger<ISoftDelete>
{
    readonly IApplicationDbContext _applicationDbContext;

    public EnsureSoftDeletedTrigger(ApplicationDbContext applicationDbContext) {
        _applicationDbContext = applicationDbContext;
    }

    public Task BeforeSave(ITriggerContext<ISoftDelete> context, CancellationToken cancellationToken) {
        if (context.ChangeType == ChangeType.Deleted) {
            context.Entity.DeletedOn = DateTime.UtcNow;
            _applicationDbContext.Entry(context.Entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
        }
    } 
}

Any entity that now implements the ISoftDelete interface will be soft-deleted.

Clone this wiki locally