ASP.NET Core 7 MVC中无法创建IdentityUser的DbSet该如何解决?
解决方法
这个错误的核心原因是项目中仍有代码在引用默认的IdentityUser,但你的DbContext只注册了自定义的ApplicationUser,按以下步骤修复:
- 修正Program.cs中的身份服务配置
打开项目根目录的Program.cs,找到身份注册的代码段,将所有IdentityUser替换为你的自定义ApplicationUser:
如果是使用AddDefaultIdentity:
// 原来的错误代码 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); // 修改为 builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>();
如果是使用AddIdentity(自定义角色等场景):
// 原来的错误代码 builder.Services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // 修改为 builder.Services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
- 替换所有业务代码中的
IdentityUser引用
检查项目中涉及用户操作的部分,比如注册/登录控制器、ViewModel等,把所有IdentityUser类型替换为ApplicationUser。
比如注册页面的RegisterModel中创建用户的代码:
// 原来的代码 var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; // 修改为 var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
- 验证并重启项目
完成上述修改后,重新编译项目,启动后尝试登录/注册操作,错误即可解决。如果仍有问题,可删除之前的迁移文件,重新执行:
dotnet ef migrations add InitialCustomUser dotnet ef database update
注意:如果数据库已有生产数据,删除迁移前请做好数据备份。
内容的提问来源于stack exchange,提问作者Daniel Haven
相关产品推荐
相关产品推荐

