-
Notifications
You must be signed in to change notification settings - Fork 12
How events work
The term events covers a wide range of applications and implementations. But in this library the events are messages added to a EF Core entity class, that is a class that EF Core maps to a database. These messages aren't saved to the database, but picked up by the Event Runner when SaveChanges or SaveChangesAsync is called and cause specific code you have written, known as event handlers to run.
There are three types of events, which are run at different parts of the SaveChanges / SaveChangesAsync, as shown in the figure below

- The Before events (also knows as domain events) are the most used. These allow you to add extra changes to the data being written out to the database.
- The During events (also knows as integration events) are used when you want to link two systems. Your data is saved to the application's database within an transaction before you During event(s) is called. If any During event returns an error (or exception), then the update to your application's database is rolled back and an error/exception is returned.
- The After events are only run if the SaveChanges / SaveChangesAsync was successful. They are useful for say sending an email or invalidating a cached value once you are sure the update worked.
Here is an example taken from the article A robust event-driven architecture for using with Entity Framework Core where the location of a job sets the Sales Tax. In this case we need to recalculate the price of any job done at that location if its State/County property changes. Here are the steps to make it work (assuming you have added the EfCore.GenericServices library to the various projects and set up the various parts - see Setup parts in the sidebar).
- You create a specific event, lets call it
TaxRateChangedEvent- see Creating events - You edit the property (or DDD method) that matters for the Sales Tax so that if it changes it adds a message to the entity class - see Setup: Entity classes
- Now you write an event handler that contains the code to update all the jobs at that location - see Creating event handlers.
- When
SaveChangesorSaveChangesAsyncis called the Event Runner will match your event message to the right event handler and run is.
The end result is: when the State/County property is changed and SaveChanges or SaveChangesAsync then the business logic sets the Sales Tax on all the jobs at that location.