簡體   English   中英

將身份角色聲明 Pk 類型更改為 Guid

[英]Change Identity Role Claims Pk type as Guid

我創建了一個數據上下文,其中所有身份表都以Guid 作為主鍵,但遷移后的IdentityUserClaimIdentityRoleClaim表仍然以int 作為主鍵 有什么方法可以將其更改為Guid 作為主鍵

public class DataContext: IdentityDbContext<IdentityUser<Guid>, IdentityRole<Guid>, Guid, IdentityUserClaim<Guid>, IdentityUserRole<Guid>, IdentityUserLogin<Guid>, IdentityRoleClaim<Guid>, IdentityUserToken<Guid>>
{
    public DataContext(DbContextOptions<DataContext> options): base(options)
    {
            
    }
}

在此處輸入圖像描述

自定義身份 Model說:

IdentityUserClaim 的 TKey 是為用戶的 PK 指定的類型。 在這種情況下,TKey 是字符串,因為正在使用默認值。 它不是 UserClaim 實體類型的 PK 類型。

IdentityUserClaim class 看起來像這樣:

public class IdentityUserClaim<TKey> where TKey : IEquatable<TKey>
{
    public virtual int Id { get; set; }

    public virtual TKey UserId { get; set; }

    public virtual string ClaimValue { get; set; }

    public virtual void InitializeFromClaim(Claim claim);

    public virtual Claim ToClaim();
}

可以使用 EF Core 對身份表的非主鍵字段(例如 IdentityUser 的自定義身份用戶表)應用更新遷移。 但是,對於 ASP.NET Core Identity User、Roles、Claims 表上的新主鍵類型,您不能應用 EF Core 更新腳手架。

建議完全刪除並重新創建。

應用以下內容:

  1. 刪除標識表和初始 EF Core 遷移。 這是微軟的建議:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0

  1. 修改數據庫上下文 class(已經完成)。

  2. 在 Startup ConfigureServices 添加以下內容以使用通用用戶:

    services.AddIdentity<IdentityUser>().AddEntityFrameworkStores();

  3. 從上下文重新創建數據庫表。 這可以使用以下方法完成:

    context.Database.EnsureCreated();

在啟動配置()中。

無法更新IdentityUserClaimIdentityRoleClaim表的主鍵類型。 庫內部實現依賴Id列作為 integer。

我猜您出於更安全的安全原因更喜歡 Guids 而不是 Ints。 但是,請記住,這些 id 是內部的,不應暴露在服務器之外,因此可以將它們作為整數。

當然,建議像您一樣將UserIdRoleIdstring更改為Guid RoleClaimsUserClaims表相反,這些表向客戶端公開,因此,強烈建議它們具有 Guids 主鍵而不是整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM