You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有数据库中创建ASP.NET Core 6 Identity表

把Identity表添加到现有ASP.NET Core 6数据库的解决方案

推荐方案:合并DbContext(最省心)

不需要维护两个DbContext,直接让业务用的AppDbContext继承Identity的上下文,这样所有表都会自动归到同一个数据库里。

  1. 修改AppDbContext代码:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class AppDbContext : IdentityDbContext<IdentityUser>
{
    // 这里放你的业务实体DbSet,比如:
    // public DbSet<Product> Products { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
}
  1. 简化Program.cs的DbContext注册,删掉UserDbContext的相关代码,只保留:
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("DbContextConnection") ??
                      throw new InvalidOperationException("Connection string not found")));
  1. 注册Identity服务,指定用AppDbContext存储数据:
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<AppDbContext>();

生成并应用迁移(Rider中操作)

打开Rider底部的Terminal终端,执行以下命令:

  • 如果之前没给AppDbContext做过迁移,生成包含Identity表的初始迁移:
    dotnet ef migrations add InitialWithIdentity --context AppDbContext
    
  • 如果已经有过业务表的迁移,新增一个包含Identity表的迁移:
    dotnet ef migrations add AddIdentityTables --context AppDbContext
    
  • 把迁移同步到数据库:
    dotnet ef database update --context AppDbContext
    

验证结果

启动项目后,你的现有数据库里会自动出现Identity相关的表(比如AspNetUsers、AspNetRoles、AspNetUserRoles等)。


备选:保留两个DbContext的方案

如果一定要分开业务和Identity的上下文,按以下步骤操作:

  1. 确保UserDbContext继承IdentityDbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class UserDbContext : IdentityDbContext<IdentityUser>
{
    public UserDbContext(DbContextOptions<UserDbContext> options) : base(options)
    {
    }
}
  1. 注册Identity时指定用UserDbContext:
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<UserDbContext>();
  1. 为UserDbContext生成并应用迁移:
# 生成Identity迁移
dotnet ef migrations add IdentityInit --context UserDbContext
# 同步到数据库
dotnet ef database update --context UserDbContext

注意:这种分开的方式可能会带来事务跨上下文的问题,非必要不推荐。

内容的提问来源于stack exchange,提问作者FunnyDEV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:35:37