Coder Guy
Coder Guy

Reputation: 325

Can entity framework core's change tracker detect cascaded child records?

I am using the ChangeTracker to track all the items that have been marked for deletion. However, I also want to know when a child record has also been deleted as a result of a cascading delete

This is my code.

    public override int SaveChanges()
    {
        var deletedItems = ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted);

        foreach (var entity in deletedItems)
        {
            //Log deleted row to external service
        }

        return base.SaveChanges();
    }

This tells me if Table A has been deleted, but I can't figure out how to get it to tell me which child records have also cascaded.

Any help with this? Thanks

Upvotes: 1

Views: 627

Answers (1)

Vahid Farahmandian
Vahid Farahmandian

Reputation: 6568

Please note that cascades do not happen until calling SaveChanges.

Suppose that you have two models. Blog and Post, in which Blog has one-to-many relation with Post.

When you want to delete a blog record following process will be happened:(for both optional and required relationships when a parent entity is deleted)

  1. Blog is marked as Deleted
  2. Posts initially remain Unchanged since cascades do not happen until SaveChanges
  3. SaveChanges sends deletes for both dependents/children (posts) and then the principal/parent (blog)
  4. After saving, all entities are detached since they have now been deleted from the database

Reference: https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete#entity-deletion-examples

You can check this sample which has a method to log the cascade deleted records: https://github.com/dotnet/EntityFramework.Docs/tree/master/samples/core/Saving/CascadeDelete

Upvotes: 2

Related Questions