问题描述
我想在 asp.net web api 应用程序中使用 System.Guid 类型作为我所有表的 ID.但我也使用 Asp.net Identity,它使用 string 类型的 id(也用于存储 guid).所以我想知道为什么它默认使用 string id 而不是 System.Guid ?在所有应用程序中使用哪个更好的选择 - Guid id 或 string-guid id?如果使用字符串 - 在代码或数据库中生成新 ID 的最正确和可靠的方法是什么?
I want to use System.Guid type as an id for all of my tables in asp.net web api application. But I also use Asp.net Identity, which using a string-type id (to store guids as well). So I wonder why is it using string id instead of System.Guid by default? And what is better choice to use through all the application - Guid id or string-guid id? In case of using string - what is the most proper and reliable way to generate new id - in code or in database?
推荐答案
使用 ASP.NET Core,您可以通过一种非常简单的方法为 Identity 模型指定所需的数据类型.
With ASP.NET Core, you have a very simple way to specify the data type you want for Identity's models.
第一步,覆盖 < 中的标识类字符串> 到 :
First step, override identity classes from < string> to < data type you want> :
public class ApplicationUser : IdentityUser<Guid>
{
}
public class ApplicationRole : IdentityRole<Guid>
{
}
声明你的数据库上下文,使用你的类和你想要的数据类型:
Declare your database context, using your classes and the data type you want :
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);
}
}
在您的启动类中,使用您的模型声明身份服务并声明主键所需的数据类型:
And in your startup class, declare the identity service using your models and declare the data type you want for the primary keys :
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext, Guid>()
.AddDefaultTokenProviders();
这篇关于为什么 asp.net Identity 用户 ID 是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!