为什么asp.net身份用户ID是字符串? [英] Why asp.net Identity user id is string?
问题描述
我想将 System.Guid 类型用作asp.net Web API应用程序中所有表的ID.但是我也使用Asp.net Identity,它使用 string 类型的ID(也存储向导).因此,我想知道为什么默认情况下为什么使用 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.
第一步,从<中覆盖身份类.字符串> 到<您想要的数据类型> :
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身份用户ID是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!