如何使用ASP.NET Core Identity v Preview 3.0创建自定义用户和角色?

时间:2019-05-24 14:53:17

标签: c# asp.net-core entity-framework-core identity asp.net-core-identity

创建迁移文件时,出现错误,如下所示:

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

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

是的,我的上下文中没有此列,但是在以前的版本中,没有这些列就可以工作。 我的代码是:

public class UserApp: IdentityUser
{
    [PersonalData]
    public int Year { get; set; }

    [PersonalData]
    public string Country { get; set; } 

    public List<Product> products { get; set; }
}

和上下文类:

public class ApplicationContext:DbContext
{
    public ApplicationContext()
    {

    }

    //public ApplicationContext(DbContextOptions options) : base(options) { }
    public ApplicationContext(DbContextOptions<ApplicationContext> dbContext) : base(dbContext)
    {

    } 

和一些dbset。在启动课程中,我有:

services.AddIdentity<UserApp, IdentityRole>(o =>
{
    o.Password.RequireDigit = false;

    o.Password.RequireLowercase = false;

    o.Password.RequireUppercase = false;

    o.Password.RequireNonAlphanumeric = false;

    o.Password.RequiredLength = 6;
})
  .AddEntityFrameworkStores<ApplicationContext>()
  .AddDefaultTokenProviders(); 

怎么了?真的在这个版本中,我必须在上下文中添加用户和角色的属性吗?

1 个答案:

答案 0 :(得分:2)

问题是您的ApplicationContext继承了DbContext而不是IdentityDbContext。因此,您的ApplicationContext应该如下:

public class ApplicationContext : IdentityDbContext<UserApp, IdentityRole, string>
{
    public ApplicationContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

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

    }
}