c# - 如何使 EF-Core 使用 Guid 而不是字符串作为其 ID/主键

标签 c# asp.net-core entity-framework-core asp.net-identity asp.net-identity-3

当我查看 ASP.NET 3 Identity 时,它使用 string 而不是 Guid 作为唯一主键。

在我的 Entity Framework 代码优先用户的ApplicationUser类中,我继承了Identity类

public class ApplicationUser : IdentityUser
{
}

这会导致当我创建 Entity Framework 迁移时,会使用键类型 nvarchar(450) 而不是 uniqueidentifier 创建表 aspnetusers >

当我将其与 ASP.NET Identity 2 ENtity Framework 项目进行比较时,它创建了 uniqueidentifier 的 ID 字段,而不是 nvarchar (450)

我认为 uniqueidentifier 的数据库性能主键和外键会比 nvarchar(450) 更好

有没有办法使用唯一键Guid而不是stringuniqueidentifier而不是nvarchar(450)ASP.NET Identity 3

有一个previous question如何将字符串转换为 Guid,但我希望数据库表 Id 为 Guid。

我找到了另一个question对于以前的 BETA,长度为 nvarchar(128) 时也是如此。给出的原因是并非所有数据库都支持Guids,并且为了灵 active 而进行了更改。

是否一定有一种简单的方法可以从字符串更改为 Guid,而无需重写整个 identity 3

nvarchar(450) 确实有点过分了,在创建 SQL Server 数据库约束时会给出各种警告。数据库管理员绝对不会喜欢这些警告。

最佳答案

您需要定制ApplicationUser继承自IdentityUser<TKey>和自定义角色继承自 IdentityRole<TKey>

public class ApplicationUser : IdentityUser<Guid> { }    
public class Role : IdentityRole<Guid> { }

自定义上下文类继承自IdentityDbContext<ApplicationUser, Role, TKey>并使用 Fluent api 自动生成 GUID key 。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, Guid>
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>(b =>
        {
            b.Property(u => u.Id).HasDefaultValueSql("newsequentialid()");
        });

        builder.Entity<Role>(b =>
        {
            b.Property(u => u.Id).HasDefaultValueSql("newsequentialid()");
        });
    }
}

然后在启动中将身份服务添加到容器中,如下所示

services.AddIdentity<ApplicationUser, Role>()
        .AddEntityFrameworkStores<ApplicationDbContext, Guid>()
        .AddDefaultTokenProviders()
        .AddUserStore<UserStore<ApplicationUser, Role, ApplicationDbContext, Guid>> ()
        .AddRoleStore<RoleStore<Role, ApplicationDbContext, Guid>>();

如果您尚未创建数据库,请清除migrations文件夹并运行ef命令

关于c# - 如何使 EF-Core 使用 Guid 而不是字符串作为其 ID/主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37166098/

相关文章:

c# - 在循环中执行 array.length 或 list.count 是否很昂贵

c# - 在 ASP.Net Core Web 应用程序中向 NavBar 添加下拉菜单( Bootstrap )

datatable - Asp Core 1.1、DataTable两者都存在

c# - 试图模仿 Excel 舍入让我很伤心

c# - SQL 服务器 2008 : BeginExecuteNonQuery/EndExecuteNonQuery Problem

azure - 从 ASP.NET Core 访问 Azure 应用服务 ConnectionString

sql - 当 WHERE 子句返回高比例的行时,Azure SQL 查询性能会显着降低

c# - Entity Framework Core 的 MySQL 排序规则问题

entity-framework - 为什么在我使用 Entity Framework 核心创建内存中的 sqlite 数据库时表不存在?

c# - 使用 explorer.exe 打开应用程序,但添加了设置