Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make soft delete in cascade with Entity Framework Core including navigation properties?

I can get all the entities marked as IsDeleted = true, applying query filters, where IsDeleted is a field of my entities.

Now, my question is very simple, how to make a soft delete in cascade with Entity Framework Core when I am soft deleting an entity that has navigation properties that I want to mark as IsDeleted too.

like image 896
Zinov Avatar asked Mar 12 '18 18:03

Zinov


Video Answer


1 Answers

I use following code to accomplish a cascading delete. Thanks to @Zinov and ajcvickers. Based on https://github.com/aspnet/EntityFrameworkCore/issues/11240

//..
case EntityState.Deleted:
    entry.State = EntityState.Modified;
    entry.CurrentValues["IsDeleted"] = true;
    foreach (var navigationEntry in entry.Navigations.Where(n => !n.Metadata.IsDependentToPrincipal()))
    {
        if (navigationEntry is CollectionEntry collectionEntry)
        {
            foreach (var dependentEntry in collectionEntry.CurrentValue)
            {
                HandleDependent(Entry(dependentEntry));
            }
        }
        else
        {
            var dependentEntry = navigationEntry.CurrentValue;
            if (dependentEntry != null)
            {
                HandleDependent(Entry(dependentEntry));
            }
        }
    }
    break;
}

private void HandleDependent(EntityEntry entry)
{
    entry.CurrentValues["IsDeleted"] = true;
}
like image 175
jannikb Avatar answered Sep 23 '22 01:09

jannikb