koenbeuk / EntityFrameworkCore.Triggered

Triggers for EFCore. Respond to changes in your DbContext before and after they are committed to the database.
MIT License
554 stars 29 forks source link

Triggered vs SaveChangesInterceptor #203

Closed jepzen closed 3 weeks ago

jepzen commented 1 month ago

Hi

Sorry if it is not the right way to ask questions but dont really know which other way to contact you.

I am wondering how this project is compared to SaveChangesIntercepter? Is there any reason to use this over SaveChangesInterceptor? Would be great with a comparison in the wiki if this project is still wort using.

Also do you recommend it for production ?

koenbeuk commented 1 month ago

SaveChangesInterceptors are great for simple tasks like setting a created date or implementing soft-deletes. this project uses SaveChangesInterceptors under the hood and solve some common problems with SaveChangesInterceptors:

  1. Triggers support dependency injection. You can inject your own services within your trigger instances that are then resolved from the same service scope as the one used to obtain an instance of the current DbContext.
  2. Triggers are recursive. Modifying the entity graph in a trigger can result in subsequent triggers getting invoked.
  3. Triggers provide an simplified programming model. Instead of implementing an interceptor and looking at the changed entities in there, you can just implement a trigger for a particular entityType (or interface).

I recommend looking at the StudentManager sample in this repo for a use-case

jepzen commented 1 month ago

Thanks a lot. It defiantly is easier/intuitive to use that SaveChangesInterceptors.

Im using a lot of AfterSave triggers. Lot of those trigger is about fetching other entities and manipulate them.
I wonder when i need to call SaveChanges explicit after or not. Some usecases it seems like i dont need to and others it does. Any recomendations ?

koenbeuk commented 1 month ago

IAfterSaveChanges will not automatically call SaveChanges again. You'll have to manually call SaveChanges again if this is intended. You could consider a trigger that implements IAfterSaveCompletedTrigger to perform another SaveChanges call. This will be a no-op if there are no additional changes to save. Otherwise it will raise triggers accordingly. That said, It sounds like you would want to use IBeforeSaveTrigger instead as it allows you to manipulate your entity graph when saving

jepzen commented 3 weeks ago

Thanks a lot