Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Cascade a SoftDelete?

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()
    {
        ChangeTracker.DetectChanges();

        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,

like image 690
Randy Avatar asked Oct 30 '22 21:10

Randy


1 Answers

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();
context.Parent.Remove(entity);

When I needed to grab the entire Graph like this:

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

Thank you for your input @Maarten

like image 54
Randy Avatar answered Nov 15 '22 05:11

Randy