繁体   English   中英

将 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文件夹

然后迁移和更新数据库。

有关更多详细信息,您可以查看文档: 更改主键类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM