一种解决方法是重写IdentityDbContext并使用它来映射IdentityUser和IdentityRole到不同的数据库。首先,需要在Startup.cs中注入这个新的IdentityDbContext:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));
}
在上面的代码中,我们注入了两个DbContext:ApplicationDbContext和MyIdentityDbContext。ApplicationDbContext是应用程序的主数据库,MyIdentityDbContext是专门用于Identity的新数据库。
然后,我们就可以定义MyIdentityDbContext,并在其中重写IdentityUser和IdentityRole的表名:
public class MyIdentityDbContext : IdentityDbContext
{
public MyIdentityDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity().ToTable("AspNetUsers", "identity");
builder.Entity().ToTable("AspNetRoles", "identity");
}
}
在上面的代码中,我们使用了ToTable()方法,将IdentityUser和IdentityRole映射到名为AspNetUsers和AspNetRoles的新表,这些表位于identity架构下。最后,在我们想要使用IdentityDbContext的地方,我们可以注入MyIdentityDbContext,例如:
public class MyController : Controller
{
private readonly MyIdentityDbContext _context;
public MyController(MyIdentityDbContext context)
{
_context = context;
}
public IActionResult MyAction()
{
var user = new ApplicationUser { UserName = "myuser" };
_context.Users.Add(user);
_context.SaveChanges();
return View();
}
}
在上面的代码中,我们可以看到我们是如何向MyIdentityDbContext中添加新的用户的。同时,我们也可以在其他