gpt4 book ai didi

c# - 为什么 asp.net Identity 用户 id 是字符串?

转载 作者:可可西里 更新时间:2023-11-01 03:02:01 24 4
gpt4 key购买 nike

我想使用 System.Guid 类型作为我在 asp.net web api 应用程序中所有表的 ID。但我也使用 Asp.net Identity,它使用 string 类型的 id(也用于存储 guid)。所以我想知道为什么它默认使用 string id 而不是 System.Guid ?在所有应用程序中使用什么是更好的选择 - Guid id 或 string-guid id?如果使用字符串 - 生成新 ID 的最合适和最可靠的方法是什么 - 在代码中还是在数据库中?

最佳答案

使用 ASP.NET Core,您可以通过一种非常简单的方法来指定您想要用于 Identity 模型的数据类型。

第一步,将身份类从 覆盖为 :

public class ApplicationUser : IdentityUser<Guid>
{
}

public class ApplicationRole : IdentityRole<Guid>
{
}

声明你的数据库上下文,使用你的类和你想要的数据类型:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}

然后在您的启动类中,使用您的模型声明身份服务并声明您想要的主键数据类型:

services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext, Guid>()
.AddDefaultTokenProviders();

关于c# - 为什么 asp.net Identity 用户 id 是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30029182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com