Skip to content

How events work

Jon P Smith edited this page Jan 22, 2021 · 3 revisions

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

Three types of events

One example of Before events

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).

  1. You create a specific event, lets call it TaxRateChangedEvent - see Creating events
  2. 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
  3. Now you write an event handler that contains the code to update all the jobs at that location - see Creating event handlers.
  4. When SaveChanges or SaveChangesAsync is 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.

Clone this wiki locally