如何将 IdentityDbContext 与两个数据库相关联?

How do I associate IdentityDbContext with two databases?

我有 ASP.Net Core 命令行应用程序,我在其中尝试从一个数据库复制数据到另一个数据库。所以理想情况下,我想要这样的东西

services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("FromConnection")));
services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ToConnection")));

显然,这行不通,因为泛型中的类型是相同的。 如果我可以这样做:

var fromContext = new IdentityDbContext<IdentityUser>();
var toContext = new IdentityDbContext<IdentityUser>();
services.AddDbContext(fromContext, options => options.UseSqlServer(Configuration.GetConnectionString("FromConnection")));
services.AddDbContext(toContext, options => options.UseSqlServer(Configuration.GetConnectionString("ToConnection")));

这是一个小实用程序;所以我可以(在某种程度上)在依赖注入上做出妥协——有什么办法可以做到这一点吗?

在这种情况下,我试图从身份表中复制角色和声明;所以同样的问题是 IdentityRoleIdentityRoleClaim 类 - 但第一步是单独设置 DbContext

更新:如果我像这样使用从 DbContext 派生的 类:

public class IdentityFromDbContext : IdentityDbContext<IdentityUser> { ... }
public class IdentityToDbContext : IdentityDbContext<IdentityUser> { ... }

然后我需要具备以下条件:

services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<IdentityDbContext>()

如果我要导出 IdentityFromUser 等等,我会遇到一个问题,我需要修改应用程序模型本身

您是否考虑过分离继承自您的 MyDbContext 的上下文?

OldDbContext : MyDbContextNewDbContext : MyDbContext.

您是否考虑过使用两个 DbContext 连接两个数据库而不是将数据复制到另一个数据库?您可以在 startup.cs 中注册它们并使用构造函数 DI 它们。

参考:

您可以使用命令 add-migration init -context Context1 指定迁移并使用 update-database -context Context1 更新 pmc 中的数据库。

这种情况建议你通过SQL服务器 因为Role等表有Identity字段