5

Identity の使用に関するドキュメントに従っており、新しいユーザーを登録しようとしています (登録アクションを実行しています) が、次のエラーで失敗します:

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
4

2 に答える 2

12

問題が見つかりました。私ApplicationContextは から継承してDbContextいました。に変更しましたがIdentityDbContext<ApplicationUser>、動作します。

于 2016-09-01T03:57:55.890 に答える
2

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

これは、データベースの最初のアプローチに役立ちます。

于 2017-11-09T18:02:52.373 に答える