-
Notifications
You must be signed in to change notification settings - Fork 12
Setup: Entity classes
Before an entity class (i.e. a class that EF Core maps to your database) can use events it has to have some interfaces and code added to it. There are two ways add the events code to an entity class. Here are the two approaches.
This is the simplest way to add events to an entity class. The EntityEventsBase contains all the code and interfaces to add all three event types (Before, During or After) and a way for you to add a event using the AddEvent method.
For example
public class Order : EntityEventsBase
{
public int OrderId { get; private set; }
//... other properties/code left out
private decimal _taxRatePercent;
public decimal TaxRatePercent
{
get => _taxRatePercent;
private set
{
if (value != _taxRatePercent)
AddEvent(new TaxRateChangedEvent(value));
_taxRatePercent = value;
}
}
}The EntityEventsBase class is available in the EFCore.GenericEventRunner library (or in the EFCore.GenericEventRunner.DomainParts NuGet package).
This requires to write more code, but means you can define what events you want to support. There are three interfaces:
-
IEntityWithBeforeSaveEventswhich adds Before events to the entity -
IEntityWithDuringSaveEventswhich adds During events to the entity -
IEntityWithAfterSaveEventswhich adds After events to the entity
You will need to implement the method for each of the interface you add, plus a way for your code to add an event. Look at the EntityEventsBase class for an example of how to add the extra fields/method.
The three interfaces are available in the EFCore.GenericEventRunner library (or in the EFCore.GenericEventRunner.DomainParts NuGet package).