Search code examples
asp.net-coreentity-framework-coreasp.net-identity

How do I associate IdentityDbContext with two databases?


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>()
    .AddEntityFrameworkStores<IdentityDbContext>()

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


Solution

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

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