编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

C#开源之触发器EntityFrameworkCore.Triggered

wxchong 2024-07-11 01:07:55 开源技术 7 ℃ 0 评论


描述

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

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

参数

来源:GitHub(264) https://github.com/koenbeuk/EntityFrameworkCore.Triggered

协议:MIT

文档:https://github.com/koenbeuk/EntityFrameworkCore.Triggered/wiki

示例

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

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



结尾

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

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

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

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表