Skip to content

Instantly share code, notes, and snippets.

@rozputnii
Created September 25, 2018 09:53
Show Gist options
  • Select an option

  • Save rozputnii/42275c02dc4ede71ab4bc4eec2252f25 to your computer and use it in GitHub Desktop.

Select an option

Save rozputnii/42275c02dc4ede71ab4bc4eec2252f25 to your computer and use it in GitHub Desktop.
.Net Core EF - Override DbContext.SaveChanges and apply additional checks
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
OnBeforeSaving();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = new CancellationToken())
{
OnBeforeSaving();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
protected virtual void OnBeforeSaving()
{
foreach (var entry in ChangeTracker.Entries())
switch (entry.State) {
// Write creation date
case EntityState.Added when entry.Entity is ICreationTrackable:
entry.Property(nameof(ICreationTrackable.CreatedAt)).CurrentValue = DateTime.UtcNow;
break;
// Soft delete entity
case EntityState.Deleted when entry.Entity is ISoftDeletable:
entry.State = EntityState.Unchanged;
entry.Property(nameof(ISoftDeletable.IsDeleted)).CurrentValue = true;
break;
// Write modification date
case EntityState.Modified when entry.Entity is IModificationTrackable:
entry.Property(nameof(IModificationTrackable.ModifiedAt)).CurrentValue = DateTime.UtcNow;
break;
}
}
@trolley813
Copy link

@arpanpreneur As far as I understand, ISoftDeletable entries are only marked as deleted, rather than physically deleted from the database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment