3

を持つ新しいユーザーを登録するとき、私はdocumentation for using Identityを以下だし、(レジスタアクションを実行する)新しいユーザーを登録しようとするが、それは次のエラーで失敗しています:InvalidOperationExceptionがASP .NETのコアアイデンティティとEntityFrameworkCore

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

スタートアップ:

public class ApplicationUser : IdentityUser 
{ 
} 

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

私は標準ApplicationUserを使用しています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); 
} 

私はすでに次のことを試してみました:

  • AplicationContext
  • DbSet<ApplicationUser>を追加する私はdotnet ef

答えて

7

を経由して新しい移行を作成し、適用しなかった私が見つかりました。問題。私のApplicationContextDbContextから継承されました。私はIdentityDbContext<ApplicationUser>に変更して動作します。

+0

このソリューションは、リバースエンジニアリング、つまりデータベースの最初のアプローチのために機能しますか? –

+1

この修正プログラムを適用しても同じ問題が発生しています – Jeroen

+0

Microsoft.AspNetCore.Identity.EntityFrameworkCore名前空間のIdentityDbContextを使用しているとしますか? – Jeroen

1

IdentityDbContextを継承する新しいコンテキストクラスを作成します。

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

の下に追加します。