Search code examples
mysql.netasp.net-coreidentityuser-roles

.NET 6 Table 'aspnetuserroles' doesn't exist


I'm configuring a new project on .NET 6, with jwt, identity and MySQL Mariadb with Pomelo.EntityFrameworkCore.MySql 6.0.2. The error I'm getting when I try to login is "Table 'aspnetuserroles' doesn't exist". That table doesn't exist, but because I renamed it from OnModelCreating(). I searched on internet and the solution they give is to add "base.OnModelCreating(modelBuilder);" on ApplicationDbContext, and then use ".ToTable()" to change the name of the table but I did this and still with the same problem. This is all my configuration if anyone can help:

ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<Usuario, Rol, string>
{
    protected readonly string ConnectionString;
    public ApplicationDbContext()
    {
    }
    public ApplicationDbContext(string connectionString)
    {
        ConnectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        base.OnConfiguring(options);
        options.LogTo(message => Debug.WriteLine(message), new[] { DbLoggerCategory.Database.Command.Name })
            .EnableSensitiveDataLogging()
            .UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString));
    }

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

    public virtual DbSet<Usuario> IdentityUser { get; set; }

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

        modelBuilder.Entity<IdentityUser>().ToTable("usuarios");
        modelBuilder.Entity<IdentityRole>().ToTable("roles");
        modelBuilder.Entity<IdentityUserRole>().ToTable("usuarioroles").HasKey("RoleId", "UserId");
        modelBuilder.Entity<IdentityUserLogin>().HasKey("UserId", "ProviderKey", "LoginProvider");

    }

}

The connectionString its ok because I can get the user from db, but the error is when I try to use userManager to get the roles from that user.

I tried to change the table name from UsuarioConfig file, but still the same issue.


Solution

  • maybe you should try this:

    modelBuilder.Entity<Usuario>().ToTable("usuarios");
    

    I think this works

    Why am I not using IdentityUser<TKey> Because I'm using db first, so when I tried to use IdentityUser<TKey>, I found that it doesn't work.

    The specific reason, I think this is an interesting question. Maybe we need to look at the source code or documentation