How do I associate IdentityDbContext with two databases? entity-framework-core


I have ASP.Net Core command-line application where I try to copy data from one database from another. So ideally, I would want to have something like this

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

Obviously, this won't work since the type in the generic is the same. If I could do something like this:

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")));

It's a small utility program; so I can compromise (somewhat) on the dependency injection - is there any way to accomplish this?

In this case I am trying to copy roles and claims from Identity tables; so the same problem is with IdentityRole and IdentityRoleClaim classes - but the first step is to set up DbContext separately.

UPDATE: If I were to use derived classes from DbContext like this:

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

I then need to have the following:

services.AddIdentity<IdentityUser, IdentityRole>()

And if I were to derive IdentityFromUser etc. I would get a problem that I need to modify the application model itself

9/29/2019 9:49:40 PM

Accepted Answer

Have you considered having separated contexts that inherit from your MyDbContext?

i.e. OldDbContext : MyDbContext and NewDbContext : MyDbContext.

9/24/2019 11:25:24 PM

Popular Answer

In this case, I suggest you go through SQL Server Because the Role and other tables have the Identity field

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow