Asp.Net Core 2.2 更改数据库 运行-当前用户的时间

Asp.Net Core 2.2 change database run-time by current user

我有一个 ASP.NET Core 2.2 项目,该项目使用多个客户使用的 EF Core。每个客户都有自己的数据库,该数据库具有完全相同的模式,由 IRepository(动态加载的 DBsets)管理。它是多子域项目,我想在 account.example.com 上登录使用,经过身份验证后用户将重定向到网站 B site.example.com 通过 Cookie 身份验证授权。

网站 A,位于 www.example.com

网站 B,位于 site.example.com -(我的申请)

网站 C,位于 account.example.com -(ASP.NET Identity -.Net Core 2.2)

public MydbContext(string dbName)
        { 
            this.Database.GetDbConnection().ChangeDatabase(dbName);

        }

但是它获得了在 startup.cs class 的 ConfigureServices 中添加的默认连接字符串。如何使用 Session 在 HttpContext.User 中存储来自 Cookie 的当前用户的连接字符串,并根据查询更改 DBContext 的连接字符串。

您可以将连接字符串传递给您的构造函数并使用它。 EF Core 中的模式如下所示:

public class Db : DbContext
{
    readonly string connectionString;

    public Db(string connectionString)
    {
        this.connectionString = connectionString;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(connectionString);
        base.OnConfiguring(optionsBuilder);
    }