ASP.NET Core 2.1 - IdentityUser问题 - 无法为“IdentityUser”创建DbSet此类型未包含在上下文的模型中

时间:2018-06-07 14:38:15

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

我已将代码从ASP.NET Core 2.0升级到Core 2.1。我创建了一个新的Core 2.1项目,并将我的代码移到了新项目中。我提供了我的启动样本和ApplicationDbContext

尝试登录时出现以下错误

  

无法为“IdentityUser”创建DbSet,因为此类型不是   包含在上下文的模型中。   Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityType()

startup.cs

//Core 2.1
  services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();            

////Old Core 2.0 Code
  //services.AddIdentity<ApplicationUser, IdentityRole>()
        //    .AddEntityFrameworkStores<ApplicationDbContext>()
        //    .AddDefaultTokenProviders();

ApplicationDbContext.cs

public partial class ApplicationDbContext : 
    IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> 
 options)
        : base(options)
    {
        Database.EnsureCreated();
     }
 }

我查看了以下Microsoft文章: https://blogs.msdn.microsoft.com/webdev/2018/05/30/asp-net-core-2-1-0-now-available/

https://docs.microsoft.com/en-us/aspnet/core/migration/20_21?view=aspnetcore-2.1

4 个答案:

答案 0 :(得分:11)

尝试将public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser>更改为public partial class ApplicationDbContext : IdentityDbContext<IdentityUser>

编译器将使用提供给通用IdentityDbContext<TUser>类的类型生成DbSet

答案 1 :(得分:5)

从您的startup.cs更改

services.AddDefaultIdentity<IdentityUser>()

收件人

services.AddDefaultIdentity<ApplicationUser>()

答案 2 :(得分:2)

作为后续措施,为避免出现下一个可能的问题,在此问题已解决的情况下:您还必须更改Views\Shared_LoginPartial.cshtml

中的类型

来自

@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

收件人

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

答案 3 :(得分:0)

ApplicationDbContext更改为:

private static bool _Created = false;

public ApplicationDbContext()
{
    if (!_Created)
    {
        _Created = true;
        Database.EnsureCreated();

    }
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(@"server = .\SQLSERVER; initial catalog = DBName; Integrated Security = True; MultipleActiveResultSets = True; App = EntityFramework & quot; ");
}

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
}