【问题标题】:"Cannot create a DbSet for 'IdentityUser' this type is not included in the model for the context" issue in ASP.Net Core 7 MVC\"Cannot create a DbSet for \'IdentityUser\' this type is not included in the model for the context\" ASP.Net Core 7 MVC 中的问题
【发布时间】:2022-11-13 12:53:37
【问题描述】:

先说一些关于我的信息

  • 计算机: MacBook Pro 2019
  • .NET 核心版本: 7
  • ASP.Net 项目类型: ASP.Net 核心 MVC
  • IDE: 视觉工作室代码

问题

如果您为 IdentityUser 使用自定义模型,则必须创建一个用户模型(即“ApplicationUser”),然后让它扩展 IdentityUser,如下所示:

using System;
using Microsoft.AspNetCore.Identity;

namespace App.Models
{
    public class ApplicationUser : IdentityUser
    {
        // TODO: Write my custom fields, relations, etc.
    }
}

然后进入数据库上下文(即“ApplicationDbContext”),通常位于 Data 文件夹中。

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using App.Models;
using Microsoft.AspNetCore.Identity;

namespace App.Data;

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

在本例中,您将 ApplicationUser 设置为 IdentityUser 的覆盖。

因此,一旦您完成此操作并运行 dotnet ef migrations add &lt;your-migration-name&gt;dotnet ef database update,您就可以在 Visual Studio Code、Visual Studio 或您的编码所在的任何 IDE 上运行调试器,并让网站出现在您面前。

您现在遇到的问题是,当您尝试以现有用户身份登录或注册为新用户时,您会遇到类似于此屏幕的内容。

我该怎么办?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-7.0


    【解决方案1】:

    您必须进入_LoginPartial.cshtml 并更改注射:

    @using Microsoft.AspNetCore.Identity
    @inject SignInManager<IdentityUser> SignInManager
    @inject UserManager<IdentityUser> UserManager
    

    @using Microsoft.AspNetCore.Identity
    @inject SignInManager<ApplicationUser> SignInManager
    @inject UserManager<ApplicationUser> UserManager
    

    在我的版本中,我没有Startup.cs 文件。相反,我有一个 Program.cs 文件。在该文件中,您应该找到:

    
    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    并将其更改为:

    
    builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    然后重新启动您的调试器,您网站的用户部分应该不会再有任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2022-06-17
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多