Reputation: 325
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
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)
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