Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created October 27, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/679423189eff65989b28e796ba87d049 to your computer and use it in GitHub Desktop.
Save NickStrupat/679423189eff65989b28e796ba87d049 to your computer and use it in GitHub Desktop.
Soft-deletable entities
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