6

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,

Community
  • 1
  • 1
Randy
  • 1,137
  • 16
  • 49
  • I saw [this link](http://stackoverflow.com/a/13308176/261050) on the right of this SO page. – Maarten Aug 17 '16 at 14:27
  • @Maarten I saw that, but a Trigger cannot check if an record has inherited ISoftDeletable. – Randy Aug 17 '16 at 14:33
  • 1
    You can add triggers to the database in the migration-code, based on the presence of ISoftDeletable. – Maarten Aug 17 '16 at 14:35

1 Answers1

2

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

Community
  • 1
  • 1
Randy
  • 1,137
  • 16
  • 49