12

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

+0

“为什么”解释[这里](http://stackoverflow.com/q/19238621/304683) - 在这篇文章中的答案将真正帮助。心连心。 – EdSF

+0

感谢@EdSF,但是我仍然对组织应用程序的最佳方式是什么 - string-guids或guids(uniqueidentifier)的id? – Ostap

+0

这取决于你的要求。请参阅[Rick Anderson(MSFT)的答案](http://stackoverflow.com/a/24152085/304683)以获取指导。 – EdSF

回答

0

取决于您使用的是哪种版本的ASP.Net身份验证,数据库上的ASP.NET Identity v2应将其存储为AspNetUsers表中的唯一标识符(Guid)。在更多的前面版本中,它将在webpages_Membership表中将用户标识存储为int。

我相信它将它表现为一个字符串,因此它可以是任何您喜欢的数据类型,然后可以根据需要在代码中进行转换。

+0

您好,我正在使用最新版本的ASP.NET成员资格系统 - ASP.NET身份。我仍然不确定,对数据库中的所有表使用字符串的最佳做法是什么?或者将所有内容都转换为GUID? – Ostap

+0

@ user3460585 int vs Guids是古老的论点。看到这些答案:http://dba.stackexchange.com/a/266/6868 http://blog.codinghorror.com/primary-keys-ids-versus-guids/ http://programmers.stackexchange.com/a/189031/86760 – trailmax

+0

对不起,我没有意识到你在问你的数据库。通常我们所做的就是将用户名记录存储在我们的数据库中的用户记录中,然后我们可以引用ASP.Net记录,同时也将您从基础成员层中分离出来。 – Tim

5

使用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); 
     } 
    } 

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

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

有关信息,现在官方文档中有一个主题:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-primary-key-configuration – AdrienTorris

相关问题