ASP.NETCoreIdentity如何在不同的数据库中创建用户
创始人
2024-09-17 21:30:36
0

一种解决方法是重写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中添加新的用户的。同时,我们也可以在其他

相关内容

热门资讯

6分钟学习!雀友会广东潮汕辅助... 6分钟学习!雀友会广东潮汕辅助,hhpoker免费辅助器,攻略教程(有挂方式)-哔哩哔哩运雀友会广东...
四分钟绝活儿!新道游正版辅助,... 四分钟绝活儿!新道游正版辅助,卡农辅助,2025版教程(有挂教程)-哔哩哔哩该软件可以轻松地帮助玩家...
2分钟诀窍!微友辅助器免费版v... 2分钟诀窍!微友辅助器免费版v3.0,川友汇挂牌,透牌教程(有挂教学)-哔哩哔哩1、微友辅助器免费版...
3分钟讲义!甘肃白银麻将辅助软... 3分钟讲义!甘肃白银麻将辅助软件,微信边锋辅助软件,靠谱教程(的确有挂)-哔哩哔哩1、玩家可以在甘肃...
三分钟诀窍!福建兄弟十三水辅助... 三分钟诀窍!福建兄弟十三水辅助器下载,欢乐茶馆辅助,揭秘教程(存在有挂)-哔哩哔哩一、福建兄弟十三水...
6分钟资料!摸一把游戏辅助软件... 6分钟资料!摸一把游戏辅助软件,小闲辅助神器,解密教程(真实有挂)-哔哩哔哩1、进入到摸一把游戏辅助...
第9分钟讲义!人海大厅辅助插件... 第9分钟讲义!人海大厅辅助插件,拱趴大菠萝修改器,爆料教程(有挂教学)-哔哩哔哩人海大厅辅助插件辅助...
3分钟教程书!新众乐辅助,情怀... 3分钟教程书!新众乐辅助,情怀娱乐辅助器,德州论坛(有挂存在)-哔哩哔哩1、首先打开情怀娱乐辅助器最...
十分钟资料!白银胡乐白银版辅助... 十分钟资料!白银胡乐白银版辅助,小程序边锋辅助,普及教程(有挂工具)-哔哩哔哩1、白银胡乐白银版辅助...
第四分钟策略!途游手游辅助脚本... 第四分钟策略!途游手游辅助脚本平台,海盗来了辅助器最新,wpk教程(有挂实锤)-哔哩哔哩1、每一步都...