entity-framework - ASP.Net.Core 2.2 身份更改 ID 从字符串到 int

标签 entity-framework asp.net-core asp.net-identity visual-studio-2019

我正在尝试将 Users 表的 ID 从字符串 (GUID) 更改为 int 并且非常困难。我看过很多示例,但它们似乎适用于早期版本的 Identity 或 vs,并且由于多种原因它们不起作用。

我要么得到一个编译器错误

'Microsoft.AspNetCore.Identity.IdentityUser', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[TUser,TContext,TKey,TUserClaim,TUserLogin,TUserToken]' violates the constraint of type 'TUser'.

或者当我创建迁移时,我仍然得到 ID 的字符串列,而不是我预期的 int。

我使用的是 vs2019。 Asp.Net.Core 2.2 和 Microsoft.AspNetCore.Identity 2.2

有人能帮帮我吗?谢谢!

最佳答案

首先如下扩展IdenityUser类,这样就可以添加自定义属性了:

public class ApplicationUser : IdentityUser<int>
{
}

如果您也在应用程序中使用 Role,则扩展 IdentityRole 类。即使您不想使用它,您也可以安全地保存它:

public class ApplicationRole : IdentityRole<int>
{
}

现在您的 ApplicationDbContext 应该如下所示:

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

现在在 Startup 类的 ConfigureServices 方法中如下所示:

public void ConfigureServices(IServiceCollection services)
{
   services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

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

工作完成!现在运行一个全新的迁移并应用它。

关于entity-framework - ASP.Net.Core 2.2 身份更改 ID 从字符串到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147591/

相关文章:

php - 使用实体管理器从表中选择列的最大值的最简单、最简单的方法是什么?

vb.net - 无法为标识列插入显式值

c# - EF6 代码优先 : Using Fluent API to declare a Foreign Key

c# - ASP.Net Core 中间件无法设置异常状态码,因为 "response has already started"

c# - ASP.NET Identity 检查自定义 UserValidator 实现中是否存在电子邮件

asp.net-core - 返回 401 而不是重定向 identityserver

asp.net-core - 无法使用 ASP.NET Core Web 应用程序在 VS.2017 中启用迁移

c# - List<> 与 IEnumerable<>,在定义新类或新 View 模型类时

asp.net-core - ASP.Net Core Razor 页面 : How to return the complex model on post?

asp.net-core - 在asp net core中通过代码触发健康检查