Search code examples
c#asp.net-coreentity-framework-coreidentityasp.net-core-identity

How i can create custom user and role with ASP.NET Core identity v preview 3.0?


When i'm creating migrates, i get error, something like this:

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.

Yeah, i don't have this columns in my context, but in previus version, it`s working without that. My code is:

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

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

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

and Context class:

public class ApplicationContext:DbContext
{
    public ApplicationContext()
    {

    }

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

    } 

with some dbset. In startup class, i have :

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

What's wrong? And really in this version i must add to my context User's and Role's property?


Solution

  • Problem is your ApplicationContext is inheriting DbContext instead of IdentityDbContext. So your ApplicationContext should be as follows:

    public class ApplicationContext : IdentityDbContext<UserApp, IdentityRole, string>
    {
        public ApplicationContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
    
        }
    }