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

c# entity-framework-core

Question

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.

1
5
3/13/2018 5:13:06 PM

Popular Answer

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;
}
2
7/28/2018 9:54:51 AM


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