Skip to content

Instantly share code, notes, and snippets.

@abdusco
Created April 13, 2020 08:51
Show Gist options
  • Save abdusco/9fba58eb276897b48482065fd55f25b6 to your computer and use it in GitHub Desktop.
Save abdusco/9fba58eb276897b48482065fd55f25b6 to your computer and use it in GitHub Desktop.
c# soft delete
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Scratch.Core.Shared;
namespace Scratch.Infrastructure.Data
{
public class DbContextBase : DbContext
{
public DbContextBase()
{
}
public DbContextBase(DbContextOptions options) : base(options)
{
}
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = default)
{
SaveChanges(acceptAllChangesOnSuccess);
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
ChangeTracker.DetectChanges();
SoftDeleteEntities();
UpdateTimestamps();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
private void UpdateTimestamps()
{
var modified = ChangeTracker.Entries<IHasTimestamps>()
.Where(e => e.State == EntityState.Modified);
foreach (var item in modified)
{
item.Entity.Modified = DateTime.Now;
}
}
private void SoftDeleteEntities()
{
var deleted = ChangeTracker.Entries<ISoftDelete>()
.Where(e => e.State == EntityState.Deleted);
foreach (var item in deleted)
{
// dont remove the record
item.State = EntityState.Unchanged;
// but mark it as deleted
item.Entity.IsDeleted = true;
}
}
}
}
using System;
namespace Scratch.Core.Shared
{
public interface IHasTimestamps
{
DateTime Created { get; }
DateTime Modified { get; set; }
}
public interface ISoftDelete
{
bool IsDeleted { get; set; }
}
public abstract class Entity : IHasTimestamps, ISoftDelete
{
public Guid Id { get; protected set; }
public DateTime Created { get; } = DateTime.Now;
public DateTime Modified { get; set; }
public bool IsDeleted { get; set; } = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment