Created
April 13, 2020 08:51
-
-
Save abdusco/9fba58eb276897b48482065fd55f25b6 to your computer and use it in GitHub Desktop.
c# soft delete
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
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; | |
} | |
} | |
} | |
} |
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
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