How do I Cascade a SoftDelete?

c# entity-framework-6 soft-delete

Question

After looking through the following SO articles in no way succeeding: 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...

My entity models are using SoftDelete. I have taken control.SaveChanges() in my situation

    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();
    }

CascadeOnDelete is set for my child entities. Since I replace the deletedEntityState There is no cascade. Anyone with knowledge on how to include just the Navigation attributes in aforeach loop? Or an improved method for managing SoftDeletes?

I'm grateful in advance.

1
4
5/23/2017 10:33:50 AM

Accepted Answer

Zzz-5-Zzz after reading this SO Article...

I saw that I was capturing and removing my object as follows:

var entity = context.Parent.FirstOrDefault();
context.Parent.Remove(entity);

When I had to copy the complete graph in this manner:

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

I appreciate your thoughts. @Maarten

2
5/23/2017 12:34:57 PM


Related Questions





Related

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