Created
October 27, 2016 19:19
-
-
Save NickStrupat/679423189eff65989b28e796ba87d049 to your computer and use it in GitHub Desktop.
Soft-deletable entities
This file contains 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
interface ISoftDeletable { | |
DateTime? Deleted { get; set; } | |
} | |
class MyEntity : ISoftDeletable { | |
public Int64 Id { get; set; } | |
public String Name { get; set; } | |
public DateTime? Deleted { get; set; } | |
} | |
class MyDbContext : DbContext { | |
public DbSet<MyEntity> MyEntities { get; set; } | |
private void ProcessDeletes() { | |
var softDeletableEntries = ChangeTracker.Entries<ISoftDeletable>(); | |
foreach (var sde in softDeletableEntries) { | |
if (sde.State == EntityState.Deleted && sde.Entity.Deleted == null) { | |
sde.Entity.Deleted = DateTime.UtcNow; | |
sde.State = EntityState.Modified; // Prevent the hard delete, but allow the modified `Deleted` field to be persisted | |
} | |
} | |
} | |
public override Int32 SaveChanges() { | |
ProcessDeletes(); | |
return base.SaveChanges(); | |
} | |
public override Task<Int32> SaveChangesAsync(CancellationToken cancellationToken) { | |
ProcessDeletes(); | |
return base.SaveChangesAsync(cancellationToken); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment