使用ASP .NET Core身份和EntityFrameworkCore注册新用户时出现InvalidOperationException

编程入门 行业动态 更新时间:2024-10-25 18:32:42
本文介绍了使用ASP .NET Core身份和EntityFrameworkCore注册新用户时出现InvalidOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在遵循有关使用身份的文档并且正在尝试注册新用户(执行register操作),但是失败并出现以下错误:

I'm following the documentation for using Identity and am trying register a new user (executing the register action), but it fails with the following error:

InvalidOperationException:无法创建DbSet for'ApplicationUser',因为此类型未包含在上下文模型中。

InvalidOperationException: Cannot create a DbSet for 'ApplicationUser' because this type is not included in the model for the context.

启动:

services.AddIdentity<ApplicationUser, IdentityRole>(options => { //password options options.Password.RequireDigit = false; // ... })

我正在使用标准的ApplicationUser:

I am using a standard ApplicationUser:

public class ApplicationUser : IdentityUser { }

在AccountController中注册操作:

Register action in AccountController:

public async Task<IActionResult> Register(RegisterViewModel viewModel) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = viewModel.UserName, Email = viewModel.Email }; var result = await _userManager.CreateAsync(user, viewModel.Password); //<-- Exception happens here if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToAction(nameof(HomeController.Index), "Home"); } string errorData = ""; foreach (var error in result.Errors) { errorData += error.Description + '\n'; } StoreErrorMessage("Failed to create the user!", errorData); } return View(viewModel); }

我已经尝试过以下操作:

I already tried the following:

  • 将 DbSet< ApplicationUser> 添加到 AplicationContext
  • 我确实通过 dotnet ef
  • Adding DbSet<ApplicationUser> to AplicationContext
  • I did create and apply a new migration via dotnet ef
推荐答案

我发现了问题。我的 ApplicationContext 是从 DbContext 继承的。我将其更改为 IdentityDbContext< ApplicationUser> ,它可以正常工作。

I found the problem. My ApplicationContext was inheriting from DbContext. I changed it to IdentityDbContext<ApplicationUser> and it works.

更多推荐

使用ASP .NET Core身份和EntityFrameworkCore注册新用户时出现InvalidOperationException

本文发布于:2023-11-17 04:29:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:新用户   身份   NET   ASP   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!