百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

EntityFrameworkCore.Triggered

> 编程语言
开源

EFCore 触发器。在更改被提交到数据库之前和之后,响应 DbContext 中的变化。

595 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

EFCore 触发器。在更改被提交到数据库之前和之后,响应 DbContext 中的变化。

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

  1. Install the package from NuGet
  2. Write triggers by implementing IBeforeSaveTrigger and IAfterSaveTrigger
  3. Register your triggers with your DbContext
  4. View our samples and more samples and a sample application
  5. Check out our wiki for tips and tricks on getting started and being successful.

Example

…

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:

csharp
    services
        .AddDbContext(options => options.UseTriggers())
        .AddTransient, MyBeforeSaveTrigger>();

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:

csharp
services.AddDbContext(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.

csharp
services.AddDbContextPool(...); // Before
services.AddTriggeredDbContextPool(...); // After

Cascading changes (previously called Recursion)

BeforeSaveTrigger 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:

csharp
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:

csharp
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. 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:

…

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 will be included within the transaction and changes made in IAfterSaveTrigger 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:

…

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.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#dotnetefcoreentity-frameworkentity-framework-core

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言