如何在现有数据库中创建ASP.NET Core 6 Identity表
把Identity表添加到现有ASP.NET Core 6数据库的解决方案
推荐方案:合并DbContext(最省心)
不需要维护两个DbContext,直接让业务用的AppDbContext继承Identity的上下文,这样所有表都会自动归到同一个数据库里。
- 修改
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) { } }
- 简化
Program.cs的DbContext注册,删掉UserDbContext的相关代码,只保留:
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("DbContextConnection") ?? throw new InvalidOperationException("Connection string not found")));
- 注册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的上下文,按以下步骤操作:
- 确保
UserDbContext继承IdentityDbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class UserDbContext : IdentityDbContext<IdentityUser> { public UserDbContext(DbContextOptions<UserDbContext> options) : base(options) { } }
- 注册Identity时指定用
UserDbContext:
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<UserDbContext>();
- 为
UserDbContext生成并应用迁移:
# 生成Identity迁移 dotnet ef migrations add IdentityInit --context UserDbContext # 同步到数据库 dotnet ef database update --context UserDbContext
注意:这种分开的方式可能会带来事务跨上下文的问题,非必要不推荐。
内容的提问来源于stack exchange,提问作者FunnyDEV
相关产品推荐
相关产品推荐

