【问题标题】:Determine connection string based on a config value根据配置值确定连接字符串
【发布时间】:2018-10-18 12:43:05
【问题描述】:

我用.Net Core

我有一个场景,我需要根据部门 ID 将连接字符串切换到具有相同架构的两个不同数据库。

我有一个名为 Department1 的数据库,其中存放了旧记录,管理层的决定是通过在我们的 Config 数据库中更新逗号分隔的切换设置 DepartmentToggle 来定期将各个部门记录移动到 Department2。基本上,我们的 ETL 团队会将记录移至新数据库,并在完成后更新此设置。长期计划是将这些数据库记录移至云端。这是第一步。

因此,如果切换设置DepartmentToggle 的值为"1,2,3",则表示部门1、2、3 记录在Department2 中。所以,我必须首先从Config 数据库中读取DepartmentToggle 配置值,检查DepartmentId 是否包含在切换中。如果是,DepartmentContext 必须使用Department2 连接字符串。下面是我的上下文类:

public partial class DepartmentContext : DbContext
{
    // Required for DI container
    public DepartmentContext() { }
    // Required for unit testing
    public DepartmentContext(DbContextOptions options) : base(options) {}

    public virtual DbSet<Faculty> Faculties { get; set; }
    public virtual DbSet<Student> Students { get; set; }
    ......
    //More DbSets

    //connectionString to change based on the DepartmentId
    public static string ConnectionString { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(ConnectionString);
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //modelBuilder.Entity<Faculty>(entity => { });
    }
}

有什么建议吗?

【问题讨论】:

  • 如果您有什么想在我的回答中进一步澄清的地方,请告诉我

标签: c# entity-framework-core asp.net-core-2.0 asp.net-core-webapi


【解决方案1】:

你可以通过以下方式做到这一点。

public class DepartmentContext : DbContext
{
    public DepartmentContext(
        IDepartmentRequestContext deptRequestContext, 
        IConnectionSelector connSelector) 
    : base(connSelector.GetConnectionString(deptRequestContext.SelectedDepartament))
    {
    }
}

使用 Scoped 生命周期注册(或 PerRequest,具体取决于您的容器)创建 DepartmentRequestContext 类。然后您可以创建一个中间件或请求处理程序,它将根据您从 Config Db 加载的 1、2、3 设置 SelectedDepartment 值。因为 SelectedDepartment 驻留在 Scoped 实例中,所以在创建期间您的 Department 上下文中将提供相同的值。

然后在您的 ConnectionSelector 中,您基本上可以根据 SelectedDepartment 读取 IOptions 并检索适当的连接字符串。

整个解决方案基于这样一个事实,即 DepartmentContext 应该在部门已知并缓存在中间件中之后创建。

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多