如何让两个不同的用户来处理 EF 核心迁移和 CRUD

时间:2021-04-01 05:00:28

标签: docker .net-core entity-framework-core ef-core-3.1

我正在寻找一种解决方案来处理两个不同的 SQL 用户,一个是执行 EF 核心迁移的超级用户,一个是处理应用程序 CRUD 的低权限用户。但是,解决方案是 dockerize 应用程序,并且 SQL 用户应该能够作为 env 变量传递。

1 个答案:

答案 0 :(得分:2)

您可以尝试覆盖 DbContext 中的 OnConfiguring 方法,然后您可以根据某些条件设置不同的连接字符串(不同的用户)。

.AddDbContext 扩展方法将 DbContext 注册为作用域服务,因此您应该能够处理 DbContext 的每个实例化的目的。

我会试着告诉你它的想法:

public class ApplicationDbContext : IdentityDbContext
{
    private readonly IConfiguration configuration;
    public ApplicationDbContext(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    {
        bool someCondition = true;
        builder.UseSqlServer(configuration.GetConnectionString(someCondition ? "SuperUserConnectionString" : "CrudConnectionString"));
    }
}