EntityFrameworkCore.Triggered.Abstractions
4.0.0-preview.1
dotnet add package EntityFrameworkCore.Triggered.Abstractions --version 4.0.0-preview.1
NuGet\Install-Package EntityFrameworkCore.Triggered.Abstractions -Version 4.0.0-preview.1
<PackageReference Include="EntityFrameworkCore.Triggered.Abstractions" Version="4.0.0-preview.1" />
paket add EntityFrameworkCore.Triggered.Abstractions --version 4.0.0-preview.1
#r "nuget: EntityFrameworkCore.Triggered.Abstractions, 4.0.0-preview.1"
// Install EntityFrameworkCore.Triggered.Abstractions as a Cake Addin #addin nuget:?package=EntityFrameworkCore.Triggered.Abstractions&version=4.0.0-preview.1&prerelease // Install EntityFrameworkCore.Triggered.Abstractions as a Cake Tool #tool nuget:?package=EntityFrameworkCore.Triggered.Abstractions&version=4.0.0-preview.1&prerelease
EntityFrameworkCore.Triggered 👿
Triggers for EF Core. Respond to changes in your DbContext before and after they are committed to the database.
NuGet packages
- EntityFrameworkCore.Triggered
- EntityFrameworkCore.Triggered.Abstractions
- EntityFrameworkCore.Triggered.Transactions
- EntityFrameworkCore.Triggered.Transactions.Abstractions
- EntityFrameworkCore.Triggered.Extensions
Getting started
- Install the package from NuGet
- Write triggers by implementing
IBeforeSaveTrigger<TEntity>
andIAfterSaveTrigger<TEntity>
- Register your triggers with your DbContext
- View our samples and more samples and a sample application
- Check out our wiki for tips and tricks on getting started and being successful.
Example
class StudentSignupTrigger : IBeforeSaveTrigger<Student> {
readonly ApplicationDbContext _applicationDbContext;
public class StudentTrigger(ApplicationDbContext applicationDbContext) {
_applicationDbContext = applicationDbContext;
}
public Task BeforeSave(ITriggerContext<Student> context, CancellationToken cancellationToken) {
if (context.ChangeType == ChangeType.Added){
_applicationDbContext.Emails.Add(new Email {
Student = context.Entity,
Title = "Welcome!";,
Body = "...."
});
}
return Task.CompletedTask;
}
}
class SendEmailTrigger : IAfterSaveTrigger<Email> {
readonly IEmailService _emailService;
readonly ApplicationDbContext _applicationDbContext;
public StudentTrigger (ApplicationDbContext applicationDbContext, IEmailService emailservice) {
_applicationDbContext = applicationDbContext;
_emailService = emailService;
}
public async Task AfterSave(ITriggerContext<Student> context, CancellationToken cancellationToken) {
if (context.Entity.SentDate == null && context.ChangeType != ChangeType.Deleted) {
await _emailService.Send(context.Enity);
context.Entity.SentDate = DateTime.Now;
await _applicationContext.SaveChangesAsync();
}
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set;}
}
public class Email {
public int Id { get; set; }
public Student Student { get; set; }
public DateTime? SentDate { get; set; }
}
public class ApplicationDbContext : DbContext {
public DbSet<Student> Students { get; set; }
public DbSet<Email> Emails { get; set; }
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<EmailService>();
services
.AddDbContext<ApplicationContext>(options => {
options.UseTriggers(triggerOptions => {
triggerOptions.AddTrigger<StudentSignupTrigger>();
triggerOptions.AddTrigger<SendEmailTrigger>();
});
})
.AddTransient<IEmailService, MyEmailService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ ... }
}
Related articles
Triggers for Entity Framework Core - Introduces the idea of using EF Core triggers in your codebase
Youtube presentation - Interview by the EF Core team
Trigger discovery
In the given example, we register triggers directly with our DbContext. This is the recommended approach starting from version 2.3 and 1.4 respectively. If you're on an older version then it's recommended to register triggers with your application's DI container instead:
services
.AddDbContext<ApplicationContext>(options => options.UseTriggers())
.AddTransient<IBeforeSaveTrigger<User>, MyBeforeSaveTrigger<User>>();
Doing so will make sure that your triggers can use other services registered in your DI container.
You can also use functionality in EntityFrameworkCore.Triggered.Extensions which allows you to discover triggers that are part of an assembly:
services.AddDbContext<ApplicationContext>(options => options.UseTriggers(triggerOptions => triggerOptions.AddAssemblyTriggers()));
// or alternatively
services.AddAssemblyTriggers();
DbContext pooling
When using EF Core's DbContext pooling, Triggers internally needs to discover the IServiceProvider
that was used to obtain a lease on the current DbContext. Thankfully, all that's complexity is hidden and all that's required is a call to AddTriggeredDbContextPool
.
services.AddDbContextPool<ApplicationDbContext>(...); // Before
services.AddTriggeredDbContextPool<ApplicationDbContext>(...); // After
Cascading changes (previously called Recursion)
BeforeSaveTrigger<TEntity>
supports cascading triggers. This is useful since it allows your triggers to subsequently modify the same DbContext entity graph and have it raise additional triggers. By default this behavior is turned on and protected from infinite loops by limiting the number of cascading cycles. If you don't like this behavior or want to change it, you can do so by:
optionsBuilder.UseTriggers(triggerOptions => {
triggerOptions.CascadeBehavior(CascadeBehavior.EntityAndType).MaxRecusion(20)
})
Currently there are 2 types of cascading strategies out of the box: NoCascade
and EntityAndType
(default). The former simply disables cascading, whereas the latter cascades triggers for as long as the combination of the Entity and the change type is unique. EntityAndType
is the recommended and default cascading strategy. You can also provide your own implemention.
Inheritance
Triggers support inheritance and sort execution of these triggers based on least concrete to most concrete. Given the following example:
interface IAnimal { }
class Animal : IAnimal { }
interface ICat : IAnimal { }
class Cat : Animal, ICat { }
In this example, triggers will be executed in the order:
- those for
IAnimal
, - those for
Animal
- those for
ICat
, and finally Cat
itself.
If multiple triggers are registered for the same type, they will execute in order they were registered with the DI container.
Priorities
In addition to inheritance and the order in which triggers are registered, a trigger can also implement the ITriggerPriority
interface. This allows a trigger to configure a custom priority (default: 0). Triggers will then be executed in order of their priority (lower goes first). This means that a trigger for Cat
can execute before a trigger for Animal
, for as long as its priority is set to run earlier. A convenient set of priorities are exposed in the CommonTriggerPriority
class.
Error handling
In some cases, you want to be triggered when a DbUpdateException
occurs. For this purpose we have IAfterSaveFailedTrigger<TEntity>
. This gets triggered for all entities as part of the change set when DbContext.SaveChanges raises a DbUpdateException. The handling method: AfterSaveFailed
in turn gets called with the trigger context containing the entity as well as the exception. You may attempt to call DbContext.SaveChanges
again from within this trigger. This will not raise triggers that are already raised and only raise triggers that have since become relevant (based on the cascading configuration).
Lifecycle triggers
Starting with version 2.1.0, we added support for "Lifecycle triggers". These triggers are invoked once per trigger type per SaveChanges
lifecyle and reside within the EntityFrameworkCore.Triggered.Lifecycles
namespace. These can be used to run something before/after all individual triggers have run. Consider the following example:
public BulkReportTrigger : IAfterSaveTrigger<Email>, IAfterSaveCompletedTrigger {
private List<string> _emailAddresses = new List<string>();
// This may be invoked multiple times within the same SaveChanges call if there are multiple emails
public Task AfterSave(ITriggerContext<Email> context, CancellationToken cancellationToken) {
if (context.ChangeType == ChangeType.Added) {
this._emailAddresses.Add(context.Address);
return Task.CompletedTask;
}
}
public Task AfterSaveCompleted(CancellationToken cancellationToken) {
Console.WriteLine($"We've sent {_emailAddresses.Count()} emails to {_emailAddresses.Distinct().Count()}" distinct email addresses");
return Task.CompletedTask;
}
}
Transactions
Many database providers support the concept of a Transaction. By default when using SqlServer with EntityFrameworkCore, any call to SaveChanges
will be wrapped in a transaction. Any changes made in IBeforeSaveTrigger<TEntity>
will be included within the transaction and changes made in IAfterSaveTrigger<TEntity>
will not. However, it is possible for the user to explicitly control transactions. Triggers are extensible and one such extension are Transactional Triggers. In order to use this plugin you will have to implement a few steps:
// OPTIONAL: Enable transactions when configuring triggers (Required ONLY when not using dependency injection)
triggerOptions.UseTransactionTriggers();
...
using var tx = context.Database.BeginTransaction();
var triggerService = context.GetService<ITriggerService>(); // ITriggerService is responsible for creating now trigger sessions (see below)
var triggerSession = triggerService.CreateSession(context); // A trigger session keeps track of all changes that are relevant within that session. e.g. RaiseAfterSaveTriggers will only raise triggers on changes it discovered within this session (through RaiseBeforeSaveTriggers)
try {
await context.SaveChangesAsync();
await triggerSession.RaiseBeforeCommitTriggers();
await context.CommitAsync();
await triggerSession.RaiseAfterCommitTriggers();
}
catch {
await triggerSession.RaiseBeforeRollbackTriggers();
await context.RollbackAsync();
await triggerSession.RaiseAfterRollbackTriggers();
throw;
}
In this example we were not able to inherit from TriggeredDbContext since we want to manually control the TriggerSession
Custom trigger types
By default we offer 3 trigger types: IBeforeSaveTrigger
, IAfterSaveTrigger
and IAfterSaveFailedTrigger
. These will cover most cases. In addition we offer IRaiseBeforeCommitTrigger
and IRaiseAfterCommitTrigger
as an extension to further enhance your control of when triggers should run. We also offer support for custom triggers. Let's say we want to react to specific events happening in your context. We can do so by creating a new interface IThisThingJustHappenedTrigger
and implementing an extension method for ITriggerSession
to invoke triggers of that type. Please take a look at how Transactional triggers are implemented as an example.
Async triggers
Async triggers are fully supported, though you should be aware that if they are fired as a result of a call to the synchronous SaveChanges
on your DbContext, the triggers will be invoked and the results waited for by blocking the caller thread as discussed here. This is known as the sync-over-async problem which can result in deadlocks. It's recommended to use SaveChangesAsync
to avoid the potential for deadlocks, which is also best practice anyway for an operation that involves network/file access as is the case with an EF Core read/write to the database.
Starting from v4 (currently in preview), we offer both synchronous and asynchronous triggers.
Versions
- V4-preview is an evolution of this library with breaking changes. This is still in production and not ready for production use.
- V3 is available for those targeting EF Core 6 or later and is the current stable offering.
- V2 Targets EF Core 3.1. This requires you to inherit from
TriggeredDbContext
or handle manual management of trigger sessions.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net6.0
- No dependencies.
NuGet packages (2)
Showing the top 2 NuGet packages that depend on EntityFrameworkCore.Triggered.Abstractions:
Package | Downloads |
---|---|
EntityFrameworkCore.Triggered
Triggers for EF Core. Respond to changes in your ApplicationDbContext before and after they are committed to the database |
|
EntityFrameworkCore.Triggered.Transactions.Abstractions
Triggers for EF Core. Respond to changes in your ApplicationDbContext before and after they are committed to the database |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
4.0.0-preview.1 | 7,292 | 3/31/2023 |
3.2.2 | 924,061 | 12/11/2022 |
3.2.1 | 126,638 | 10/24/2022 |
3.2.0 | 1,427 | 10/21/2022 |
3.2.0-preview.3 | 5,399 | 6/28/2022 |
3.1.0 | 189,144 | 5/11/2022 |
3.1.0-beta.1 | 194 | 4/19/2022 |
3.0.0 | 107,626 | 11/15/2021 |
3.0.0-beta.3 | 448 | 9/22/2021 |
3.0.0-beta.2 | 178 | 9/17/2021 |
2.4.0-beta.1 | 1,013 | 9/8/2021 |
2.3.2 | 135,818 | 6/8/2021 |
2.3.1 | 11,580 | 5/23/2021 |
2.3.0 | 8,820 | 4/28/2021 |
2.3.0-beta.2 | 591 | 4/19/2021 |
2.3.0-beta.1 | 486 | 4/12/2021 |
2.2.0 | 4,938 | 3/10/2021 |
2.1.0 | 2,978 | 1/24/2021 |
2.1.0-beta1 | 896 | 1/10/2021 |
2.0.0 | 2,320 | 11/26/2020 |
2.0.0-beta3 | 1,263 | 11/18/2020 |
2.0.0-beta2 | 1,614 | 9/27/2020 |
2.0.0-beta1 | 1,260 | 9/19/2020 |
1.4.0 | 12,374 | 4/28/2021 |
1.4.0-beta.2 | 475 | 4/19/2021 |
1.4.0-beta.1 | 161 | 4/12/2021 |
1.3.0 | 3,411 | 3/8/2021 |
1.2.0 | 1,977 | 1/24/2021 |
1.2.0-beta2 | 890 | 1/9/2021 |
1.2.0-beta1 | 1,002 | 12/22/2020 |
1.1.0 | 3,977 | 11/8/2020 |
1.1.0-beta2 | 991 | 10/24/2020 |
1.1.0-beta1 | 1,352 | 9/27/2020 |
1.0.1 | 2,055 | 9/20/2020 |
1.0.0 | 1,721 | 9/19/2020 |
1.0.0-beta.2 | 700 | 9/4/2020 |
1.0.0-beta.1 | 328 | 8/30/2020 |
0.4.2 | 1,639 | 8/23/2020 |
0.4.1 | 1,590 | 8/19/2020 |
0.4.0 | 1,397 | 8/19/2020 |
0.3.2 | 1,781 | 8/11/2020 |
0.3.1 | 1,442 | 8/11/2020 |
0.3.0 | 1,564 | 8/9/2020 |
0.2.2 | 1,521 | 7/30/2020 |
0.2.1 | 1,416 | 7/27/2020 |
0.2.0 | 1,492 | 7/25/2020 |
0.1.0 | 3,683 | 7/18/2020 |