c# – 使用ASP .NET Core Identity和EntityFrameworkCore注册新用户时出现InvalidOperationException

前端之家收集整理的这篇文章主要介绍了c# – 使用ASP .NET Core Identity和EntityFrameworkCore注册新用户时出现InvalidOperationException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在关注 documentation for using Identity并尝试注册一个新用户(执行注册操作),但它失败并出现以下错误

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:

public class ApplicationUser : IdentityUser
{
}

在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);
}

我已经尝试过以下方法

>添加DbSet< ApplicationUser>到AplicationContext
>我确实通过dotnet ef创建并应用了新的迁移

解决方法

我发现了这个问题.我的ApplicationContext继承自DbContext.我将其更改为IdentityDbContext< ApplicationUser>它的工作原理.
原文链接:https://www.f2er.com/netcore/95976.html

猜你在找的.NET Core相关文章