Asp.Net MVC Core 6.0 Identity自定义表列未在User类生效问题
ASP.NET Core 6 Identity自定义AspNetUsers表后CreateAsync抛无效列错误排查项
- 没有正确扩展
IdentityUser类且未替换Identity服务注册的默认用户类型
需先定义继承IdentityUser的自定义用户类,新增自定义字段后,在Program.cs注册Identity时显式指定该自定义类,不能使用默认的IdentityUser泛型参数:// 自定义用户类示例 public class AppUser : IdentityUser { public string CustomProp { get; set; } } // Program.cs 正确注册写法 builder.Services.AddDefaultIdentity<AppUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<YourDbContext>(); - DbContext未继承带自定义用户类的泛型
IdentityDbContext
自定义DbContext必须继承IdentityDbContext<AppUser>而非非泛型的IdentityDbContext基类,才能正确映射自定义字段到AspNetUsers表:// 正确继承写法 public class YourDbContext : IdentityDbContext<AppUser> { public YourDbContext(DbContextOptions<YourDbContext> options) : base(options) { } } UserManager注入类型错误
调用CreateAsync的位置必须注入UserManager<AppUser>,如果使用默认的UserManager<IdentityUser>,生成的SQL语句不会包含自定义字段,会直接触发无效列错误。OnModelCreating配置顺序错误或映射冲突
必须先调用基类的OnModelCreating方法加载Identity默认配置,再添加自定义字段的映射规则,同时确保配置的列名和数据库实际AspNetUsers表的列名完全一致:protected override void OnModelCreating(ModelBuilder modelBuilder) { // 优先调用基类方法,不能省略 base.OnModelCreating(modelBuilder); // 自定义字段配置 modelBuilder.Entity<AppUser>() .Property(u => u.CustomProp) .HasColumnName("CustomProp") .IsRequired(false); }- 迁移与数据库结构不匹配
确认生成的迁移文件中AspNetUsers表的结构包含所有自定义字段,执行Update-Database时如果存在多个DbContext,需显式指定-Context YourDbContext参数,避免配置应用到错误的上下文。
内容的提问来源于stack exchange,提问作者user17598374
相关产品推荐
相关产品推荐

