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

ASP.NET Core 6 MVC重命名Identity数据库模型时依赖注入报错

错误根源分析

  1. 自定义用户类名称不匹配:自定义用户类实际命名为User,但在OnModelCreating和AddDefaultIdentity中却使用了AppUser,导致依赖注入容器无法正确识别类型。
  2. ApplicationDbContext未正确注册:报错提示无法解析ApplicationDbContext服务,说明未在Program中完成DbContext的注册配置。

修复步骤

1. 统一自定义用户类名称

将自定义用户类名称改为AppUser(或把所有引用AppUser的地方替换为User,保持命名一致即可):

public partial class AppUser : IdentityUser
{
    // 若有自定义属性可在此添加
}

2. 正确注册ApplicationDbContext

在Program.cs中,先注册DbContext再添加Identity服务:

// 注册DbContext,替换为你的连接字符串名称
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 添加Identity服务,使用统一后的AppUser类型
builder.Services.AddDefaultIdentity<AppUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

3. 修正OnModelCreating的实体映射

确保所有映射使用正确的AppUser类型,补充完整Identity表的重命名配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder); 

    // 用户表
    modelBuilder.Entity<AppUser>().ToTable("Users");
    modelBuilder.Entity<AppUser>().Property(up => up.Id).HasColumnName("UserId");

    // 角色表
    modelBuilder.Entity<IdentityRole>().ToTable("Roles");
    modelBuilder.Entity<IdentityRole>().Property(r => r.Id).HasColumnName("RoleId");

    // 用户角色关联表
    modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");
    modelBuilder.Entity<IdentityUserRole<string>>().HasKey(ur => new { ur.UserId, ur.RoleId });

    // 用户声明表
    modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");

    // 用户登录表
    modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");

    // 用户令牌表
    modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
}

4. 确保ApplicationDbContext继承正确

ApplicationDbContext需继承自IdentityDbContext<AppUser>,指定自定义用户类型:

public class ApplicationDbContext : IdentityDbContext<AppUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

验证与数据库更新

完成上述修改后,执行以下命令更新数据库:

Add-Migration RenameIdentityTables
Update-Database

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:08:13