我正在 .NET 6 上配置一个新项目,其中包含 jwt、identity 和 MySQL Mariadb 以及 Pomelo.EntityFrameworkCore.MySql 6.0.2。 当我尝试登录时收到的错误是“表'aspnetuserroles'不存在”。该表不存在,但因为我从 OnModelCreating() 重命名了它。我在互联网上搜索,他们给出的解决方案是添加“base.OnModelCreating(modelBuilder);”在 ApplicationDbContext 上,然后使用“.ToTable()”更改表的名称,但我这样做了,但仍然遇到同样的问题。 这就是我的全部配置,如果有人可以帮忙的话:
应用程序DbContext:
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");
}
}
connectionString 没问题,因为我可以从数据库获取用户,但错误是当我尝试使用 userManager 从该用户获取角色时。
我尝试从 UsuarioConfig 文件更改表名称,但仍然是同样的问题。
当您想要更改这些表的名称时(IdentityUserRole <
Tkey
>、 IdentityUserToken <Tkey
>、 IdentityRoleClaim <Tkey
>、 IdentityUserClaim <Tkey
>、 IdentityUserLogin <Tkey
>),您需要指定 的类型T
(主键使用的类型),
因此将代码更改为:
builder.Entity<IdentityUserRole<string>>(entity =>
{
entity.ToTable("UserRoles");
});
然后就可以看到表名已经更改了
更多信息请参阅文档。