将 Microsoft.AspNetCore.Identity 默认表的 ID 设置为 int

setting Microsoft.AspNetCore.Identity default tables's ids to int

我需要将所有默认 ID 设置为 int,但我只实现了一个新用户 class。我使用的是 Microsoft.AspNetCore.Identity 而不是 Microsoft.AspNet.Identity

我的用户是:

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

DBAccessContext.cs 是:

public class DBAccessContext : IdentityDbContext<User>
{
    public DBAccessContext(DbContextOptions<DBAccessContext> options) : base(options)
    {

    }

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

        // Customize the ASP.NET Identity model and override the defaults if needed.
        builder.Entity<User>(entity => { entity.ToTable(name: "Users");});
        builder.Entity<IdentityRole>(entity => { entity.ToTable(name: "Roles"); });
        builder.Entity<IdentityUserRole<string>>(entity => { entity.ToTable("Roles"); });
        builder.Entity<IdentityUserClaim<string>>(entity => { entity.ToTable("Claims"); });
        builder.Entity<IdentityUserLogin<string>>(entity => { entity.ToTable("Logins"); });
        builder.Entity<IdentityRoleClaim<string>>(entity => { entity.ToTable("RoleClaims"); });
        builder.Entity<IdentityUserToken<string>>(entity => { entity.ToTable("UserTokens"); });

        //Calling the Seeding
        builder.ApplyConfiguration(new RoleConfiguration());
    }
}

最后配置如下:

    public static void ConfigureIdentity(this IServiceCollection services)
    {
        var builder = services.AddIdentityCore<User>(q => { q.User.RequireUniqueEmail = true; });
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), services);
        builder.AddEntityFrameworkStores<DBAccessContext>().AddDefaultTokenProviders();
    }

我建议你检查这个问题:

您可以通过这种方式将默认 ID 更改为 int。

用户:

public class User : IdentityUser<int>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

数据库访问上下文:

public class DBAccessContext : IdentityDbContext<User, IdentityRole<int>, int>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    //....
}

如果数据库是在 PK 更改之前创建的,运行 Drop-Database 删除数据库并删除您的 Migrations 文件夹

然后迁移和更新数据库。

更详细的可以看文档:Change the primary key type.