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

自定义Identity时执行Add-Migration命令出现数据库迁移错误

自定义Identity迁移报错修复方案

报错内容翻译

实体类型“IdentityUserLogin”需要定义主键。若希望通过约定自动识别主键,请确认实体类型配置正确且DbContext模型已完成构建。

修复步骤

  • 补全ApplicationDbContext的泛型参数,明确指定主键类型(默认用string的话要写全):
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        // 其他DbSet定义
    }
    
  • 同步ApplicationUser和ApplicationRole的继承泛型,保证主键类型一致:
    public class ApplicationUser : IdentityUser<string>
    {
        // 你的自定义属性,比如:
        public string RealName { get; set; }
    }
    
    public class ApplicationRole : IdentityRole<string>
    {
        // 自定义角色属性(按需添加)
    }
    
  • 在项目的服务配置中(.NET 6+是Program.cs,旧版本是Startup.cs),配置Identity时指定对应的用户和角色类型:
    // .NET 6+ 示例代码
    builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
  • 如果之前生成过错误的迁移文件,先清理再重新生成:
    Remove-Migration
    Add-Migration InitialIdentitySetup
    Update-Database
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:44:55