Skip to content

Setup: Entity classes

Jon P Smith edited this page Sep 12, 2020 · 3 revisions

Adding events to an entity class

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.

1. Your Entity class inherits the EntityEventsBase class

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, RefreshGrandTotalPrice));
            _taxRatePercent = value;
        }
    }
}

The EntityEventsBase class is available in the EFCore.GenericEventRunner library (or in the EFCore.GenericEventRunner.DomainParts NuGet package).

2. Apply the interfaces you need and implement the code yourself

This requires to write more code, but means you can define what events you want to support. There are three interfaces:

  1. IEntityWithBeforeSaveEvents which adds Before events to the entity
  2. IEntityWithDuringSaveEvents which adds During events to the entity
  3. IEntityWithAfterSaveEvents which 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).

Clone this wiki locally