技术方向

EntityFrameworkCore.Triggered

技术方向 数据处理
Nuget EntityFrameworkCore.Triggered
访问数 756
来源 GitHub
开源协议 MIT
星星数 264
发布时间 2022-05-24 09:06:34

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

你可以在使用EFCore将数据提交到数据库之前进行一些逻辑操作,同时在提交到数据库之后做业务逻辑的操作。


首先需要实现接口触发前和触发后的业务逻辑,你可以制定自己的业务逻辑

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();
        }
    }
}


在DbContext中配置使用触发Triggers,代码如下

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)
    { ... }
}

C#开源之触发器EntityFrameworkCore.Triggered

C#开源之触发器EntityFrameworkCore.Triggered


代码实现上还是比较简单易懂的,原理不难,感兴趣的可以自己研究代码。

如果你有审计日志的功能需求的,那么感觉使用这个库可以很方便的实现这个功能。

同时示例中带了审计功能的实现源码

频道专栏
推荐源码