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

.NET6自定义Identity用户角色表迁移时遇Host服务访问错误

ASP.NET Identity自定义角色/用户表迁移错误修复

错误根源

你的迁移报错核心是身份服务注册时的用户类型不匹配:

  • 自定义ApplicationDbContext继承IdentityDbContext时,指定的用户实体是UserInformation(自定义带额外字段的用户类)
  • 但Program.cs中AddIdentity方法传入的是默认IdentityUser,导致Identity框架的泛型约束校验失败,触发错误:

访问Microsoft.Extensions.Hosting服务时发生错误。将在没有应用服务提供程序的情况下继续。错误:类型'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]'的泛型参数[0] 'Microsoft.AspNetCore.Identity.IdentityUser'违反了'TUser'的约束。

修复步骤

1. 修正Program.cs中的身份服务注册

将AddIdentity的泛型参数替换为你自定义的UserInformation,而非默认的IdentityUser:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var configuration = builder.Configuration;
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))); 

// 替换为自定义的UserInformation,匹配DbContext的泛型参数
builder.Services.AddIdentity<UserInformation, ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// Adding Authentication

2. 清理残留迁移(可选)

如果之前已尝试生成过迁移文件,请删除项目根目录下的Migrations文件夹,避免旧的错误迁移影响新生成的内容。

3. 重新生成迁移并更新数据库

打开包管理器控制台或终端,执行以下命令:

# 生成初始迁移
Add-Migration InitialCreate
# 将迁移应用到数据库
Update-Database

额外优化点

如果后续需要添加角色种子数据,注意在SeedRoles方法中使用自定义的ApplicationRole而非默认IdentityRole,避免类型不匹配:

private void SeedRoles(ModelBuilder builder)
{
    builder.Entity<ApplicationRole>().HasData
    (
       new ApplicationRole() { Name = "Invigilator", ConcurrencyStamp = "1", NormalizedName = "INVIGILATOR" },
        new ApplicationRole() { Name = "Student", ConcurrencyStamp = "2", NormalizedName = "STUDENT" },
       new ApplicationRole() { Name = "SuperAdmin", ConcurrencyStamp = "3", NormalizedName = "SUPERADMIN" }
    ); 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:57:44