Skip to content

Setup: DbContext

Jon P Smith edited this page Sep 12, 2020 · 1 revision

How to set yo your DbContext to work with events

To use EfCore.GenericEventRunner library you have to make some changes to each of your classes that inherits EF Core's DbContext class. The library makes this easier by providing a class of type DbContextWithEvents<T>, where the T is your class that used to inherit the DbContext class. The DbContextWithEvents<T> overrides the SaveChanges and SaveChangesAsync methods to add the event handles. It also add a couple of other methods and one extra property.

You can do everything you could have done while inheriting the DbContext class, including overriding the SaveChanges and SaveChangesAsync methods yourself (but you shouldn't need too).

Here is an example of replacing the DbContext class with the DbContextWithEvents<T>, and the change you have to make to the constructor.

public class ExampleDbContext : DbContextWithEvents<ExampleDbContext>
{
    public ExampleDbContext(
        DbContextOptions<ExampleDbContext> options,   //Normal param
        IEventsRunner eventRunner = null)             //extra param for event runner
        : base(options, eventRunner)
    {
    }

    //... other code as normal
    //e.g. public DbSet<???> etc.
}

The DbContextWithEvents<T> class is available in the EFCore.GenericEventRunner library in the ForDbContext folder.

Clone this wiki locally