簡體   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