I am trying to override Savechanges in My Database Context to mark my entites as SoftDeleted.
I have an ISoftDeletable base which i override in my Entity classes
public interface IsoftDeletable
{
public bool IsDeleted {get; set;}
}
And then in my Context
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries()
.Where(p => p.State == EntityState.Deleted))
SoftDelete(entry);
return base.SaveChanges();
}
private void SoftDelete(DbEntityEntry entry)
{
var entity = entry.Entity as ISoftDeltable;
entity.IsDeleted = true;
entry.State = EntityState.Modified;
}
The above example works ok if i delete an Entity it gets soft deleted but the problem is that if that entity has Child Collections with Cascade delete, the child collections are not tracked by the Entity Framework and they are not marked as deleted.
One simple solution was to eagerly load all of the child Collections of the Entity that is going to be deleted before the delete happens so the Ef tracks the changes in the children too and soft delete them but this is a "hack" i want to avoid. It will be hard to remember all the relations between entities and eager load everything just before the delete happens. Also it will be hard to maintain this if the model changes.
Is there any better way to achieve that funcionallity?
Edit 1: I dont see how this question might be dublicate of this