EntityFrameworkCore.Triggered icon indicating copy to clipboard operation
EntityFrameworkCore.Triggered copied to clipboard

How fire trigger after delete ICollection of Entities

Open sallamia opened this issue 2 years ago • 5 comments

Hello Thank you for this wonderful extension, i have an issue whene i try to fire the trigger after deleteing IColletion of enyity.

sallamia avatar Jun 06 '22 14:06 sallamia

I'm not getting the question, can you clarify your issue? thanks.

koenbeuk avatar Jun 06 '22 16:06 koenbeuk

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.

sallamia avatar Jun 06 '22 16:06 sallamia

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(); 
    }
  }   
}

koenbeuk avatar Jun 06 '22 17:06 koenbeuk

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.

sallamia avatar Jun 07 '22 14:06 sallamia

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.

stale[bot] avatar Aug 06 '22 19:08 stale[bot]