Entity framework override save changes to soft delete entities

c# entity-framework entity-framework-6


In order to identify my entities as SoftDeleted, I'm attempting to override Savechanges in My Database Context.

In my Entity classes, I override the ISoftDeletable base.

public interface IsoftDeletable
    public bool IsDeleted {get; set;}

Afterward, in my context

public override int SaveChanges()
    foreach (var entry in ChangeTracker.Entries()
              .Where(p => p.State == EntityState.Deleted))

    return base.SaveChanges();

private void SoftDelete(DbEntityEntry entry)
   var entity = entry.Entity as ISoftDeltable;
   entity.IsDeleted = true;
   entry.State = EntityState.Modified;

The aforementioned example works as expected when I remove an entity; however, if the entity contains child collections with cascade delete, there is an issue in that the child collections are not monitored by the Entity Framework and are not tagged as destroyed.

One easy fix was to eagerly load all of the child Collections of the Entity that was about to be removed so the Ef could follow the changes in the children aswell and soft delete them before the delete happened, but this is a "hack" I want to avoid. The relations between the entities will be difficult to recall, and eager loading everything right before the deletion will be challenging. In addition, maintaining this will be challenging if the model changes.

Is there a more effective approach to make that functionality?

I don't understand how this question is similar to this, edit 1.

5/23/2017 11:46:26 AM

Popular Answer

3/8/2017 9:07:27 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow