簡體   English   中英

使用ASP .NET Core身份和EntityFrameworkCore注冊新用戶時出現InvalidOperationException

[英]InvalidOperationException when registering a new user with ASP .NET Core Identity and EntityFrameworkCore

我正在遵循使用身份文檔,並嘗試注冊一個新用戶(執行register操作),但是失敗並出現以下錯誤:

InvalidOperationException:無法為'ApplicationUser'創建DbSet,因為此類型不包含在上下文模型中。

啟動:

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> ,它可以工作。

創建繼承IdentityIbContext的新上下文類。

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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

並在startup.cs文件中添加以下代碼

services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(connection));

這將幫助您采用數據庫優先方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM