Created
September 25, 2018 09:53
-
-
Save rozputnii/42275c02dc4ede71ab4bc4eec2252f25 to your computer and use it in GitHub Desktop.
.Net Core EF - Override DbContext.SaveChanges and apply additional checks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@arpanpreneur As far as I understand,
ISoftDeletableentries are only marked as deleted, rather than physically deleted from the database.