EntityFrameworkCore.Triggered
EntityFrameworkCore.Triggered copied to clipboard
How fire trigger after delete ICollection of Entities
Hello Thank you for this wonderful extension, i have an issue whene i try to fire the trigger after deleteing IColletion of enyity.
I'm not getting the question, can you clarify your issue? thanks.
For example i have a trigger after deleting a Student and the latter is a child of the School, so when i try to delete School with a Collection of Students the trigger of Student not working.
That is controlled by the cascading behavior of this library, see: https://github.com/koenbeuk/EntityFrameworkCore.Triggered#cascading-changes-previously-called-recursion
By default, Cascading is turned on however, EF will still need to be aware of all the related entities. When you query the School record that you want to delete, make sure to also include the Student records related to that school, otherwise those will not be available tracked within the DbContext and hence, no Student triggers will fire. Hope that makes sense.
You can also implement an additional trigger that ensures that all Student records are loaded within EF so that any deletion of a School will ensure that all Student records are tracked, e.g.:
class EnsureStudentsTrackedTrigger : IBeforeSaveTrigger<School>, ITriggerPriority
{
public EnsureStudentsTrackedTrigger(MyDbContext dbContext) {
_dbContext = dbContext;
}
public int Priority => CommonTriggerPriorities.Early;
public async Task BeforeSave(ITriggerContext<School> context, CancellationToken _) {
if (context.ChangeType is ChangeType.Deleted){
// Only loads in the students when the Students navigation property is not loaded in yet
_dbContext.Entry(context.Entity).Reference(x => x.Students).LoadAsync();
// Force EF to cascade the delete status to newly loaded Student records
dbContext.ChangeTracker.CascadeChanges();
}
}
}
Thanks for your feedback. I did not understand everything, except me I want that once a School will be deleted at the same time we delete the Students childs and for each Student we trigger a Trigger.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.