ASP.NET Core Identity:如何插入自定义身份表而非AspNetUser表
解决ASP.NET Core Identity注册数据插入自定义表而非AspNetUser表的问题
你当前的问题核心是没有正确配置EF Core的DbContext和Identity服务以使用自定义的CustomIdentity用户类型,导致框架仍使用默认的AspNetUsers表。按以下步骤修复:
1. 创建自定义DbContext并继承IdentityDbContext<CustomIdentity>
默认的IdentityDbContext使用IdentityUser作为泛型参数,你需要创建自己的DbContext来指定使用CustomIdentity:
using InventoryManagement.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace InventoryManagement.Data { public class AppDbContext : IdentityDbContext<CustomIdentity> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // 可选:若需直接操作自定义用户表,可声明DbSet(IdentityDbContext已内置Users集合,此步可省略) // public DbSet<CustomIdentity> CustomIdentities => Set<CustomIdentity>(); } }
2. 在Program.cs中配置Identity服务与DbContext
确保注册服务时指定使用自定义的CustomIdentity和AppDbContext:
var builder = WebApplication.CreateBuilder(args); // 注册自定义DbContext builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); // 配置Identity服务,指定用户类型为CustomIdentity builder.Services.AddIdentity<CustomIdentity, IdentityRole>() .AddEntityFrameworkStores<AppDbContext>() // 指定使用自定义DbContext存储数据 .AddDefaultTokenProviders(); // 其他服务配置(如MVC、授权等)... var app = builder.Build(); // 中间件配置(如静态文件、路由、身份验证等)...
3. 重新生成迁移并更新数据库
之前的迁移可能是基于默认IdentityUser生成的,需要重置迁移并重新生成:
- 打开Package Manager Console(或使用.NET CLI):
- 删除旧迁移(若存在):
(若有多个旧迁移,重复执行直到无迁移可删)Remove-Migration - 创建新迁移:
Add-Migration InitCustomIdentitySchema - 更新数据库:
Update-Database
- 删除旧迁移(若存在):
4. 自定义表名(可选)
如果希望表名是CustomIdentity而非默认的AspNetUsers,在AppDbContext的OnModelCreating方法中配置表名映射:
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 将CustomIdentity实体映射到名为CustomIdentity的表 modelBuilder.Entity<CustomIdentity>().ToTable("CustomIdentity"); }
修改后需重新执行Add-Migration和Update-Database生效。
完成以上步骤后,用户注册时数据就会插入到你的自定义CustomIdentity表中,而非默认的AspNetUsers表。
内容的提问来源于stack exchange,提问作者Lakshmi Sureshan
相关产品推荐
相关产品推荐

