How do I Cascade a SoftDelete?

c# entity-framework-6 soft-delete


After checking these SO articles: cascade-delete-in-entity-framework, ef6-1-soft-delete-with-cascade-delete, cascading-soft-delete, method-for-cascading-soft-deletes-in-parent-child-relationships and reasons-for-cascading-soft-deletes and not finding a solution...

I have SoftDelete working for my Entity Models. I have overridden SaveChanges() in my Context:

    public override int SaveChanges()

        foreach (DbEntityEntry<ISoftDeletable> entity in ChangeTracker.Entries<ISoftDeletable>())
            if (entity.State == EntityState.Deleted)
                entity.State = EntityState.Modified;
                entity.Entity.IsDeleted = true;
        return base.SaveChanges();

I have set CascadeOnDelete for my Child Entities. Because I override the deleted EntityState it doesn't cascade. Does anybody know a way to put only the Navigation properties in a foreach loop? Or a better way to handle SoftDeletes?

Thank you in advance,

5/23/2017 10:33:50 AM

Accepted Answer

After reading this SO Article entity-framework-6-code-first-cascade-delete...

I realized, I was grabbing and and deleting my entity like this:

var entity = context.Parent.FirstOrDefault();

When I needed to grab the entire Graph like this:

var entity = context.Parent.Include("Children").FirstOrDefault();

Thank you for your input @Maarten

5/23/2017 12:34:57 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