【问题标题】:Change Id type of asp.net core 2.2 IdentityUser更改asp.net core 2.2 IdentityUser的Id类型
【发布时间】:2019-05-13 22:45:26
【问题描述】:

我是 dot-net core 2.x 的新手,所以...

我想将 asp.net core 2.2 IdentityUser 中的 Id 类型从 string 更改为 int。

我通过 google(和 stackoverflow 搜索工具)找到的所有示例都为我提供了 asp.net core 2.0 的示例,它在您搭建身份时提供 ApplicationUser(2.2 没有提供)。

所以,我不知所措.. 我尝试的第一件事(我寄予厚望)是:

services.AddDefaultIdentity<IdentityUser<int>>()
  .AddRoles<IdentityRole>()
  .AddDefaultTokenProviders()
  .AddEntityFrameworkStores<ApplicationDbContext>();

但是,当我尝试 Add-Migration InitialCreate -Context ApplicationDbContext 时出现以下错误:

访问“程序”类上的 IWebHost 时出错。在没有应用程序服务提供商的情况下继续。错误:GenericArguments[0],“Microsoft.AspNetCore.Identity.IdentityUser`1[System.Int32]”,在“Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole, TUserLogin,TUserToken,TRoleClaim]' 违反了 'TUser' 类型的约束

想法?想法?我可以阅读的文档?

【问题讨论】:

  • @TanvirArjel 我已经回滚了您的编辑,这使得 OP 看起来还要求更改 Role 类型的类型,但事实并非如此。

标签: c# asp.net-core asp.net-core-identity asp.net-core-2.2


【解决方案1】:

要将 IdentityUser 密钥类型从 string 更改为 int,您还需要将 IdentityDbContext 更改为 IdentityDbContext&lt;IdentityUser&lt;int&gt;,IdentityRole&lt;int&gt;,int&gt;

  1. 启动.cs

    services.AddDefaultIdentity<IdentityUser<int>>()
        .AddDefaultUI(UIFramework.Bootstrap4)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
  2. ApplicationDbContext

    public class ApplicationDbContext : IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
    
  3. 删除Migrations文件夹并删除现有数据库

  4. 运行命令添加和更新数据库

【讨论】:

  • 当我在 Identity 中添加“.AddDefaultUI(UIFramework.Bootstrap4)”时,出现错误“当前上下文中不存在名称 UIFramweork”。我应该为此下载或安装什么?
  • @CrazyCoder .AddDefaultUI(UIFramework.Bootstrap4) 在 .net core 2.2 模板中。
  • 包管理器控制台的命令是 Add-Migration 例如Add-Migration AspIdentity 要将更改应用到您的数据库:Update-Database docs.microsoft.com/en-us/ef/core/managing-schemas/migrations
  • 我还建议您阅读 the docs 以了解如何使其与 SignInManager 和其他 Idenitty 服务无缝协作。
【解决方案2】:

您可以编写自己的实现,派生自IdentityUser

public class AppUser : IdentityUser<int> 
{

}

然后注册:

services.AddDefaultIdentity<AppUser>()

如果您想向用户模型添加其他属性,这也很有用。

请记住,因为您正在更改表的主键,所以您需要重新创建这些表而不是更新它们。

【讨论】:

  • 好的,一定是缺少了什么,因为这不起作用。当我创建迁移时,用户的 ID 仍然是一个字符串。
  • @djack109 也许您以前使用string 类型而不是int 类型构建表。尝试删除所有迁移并从头开始创建它,类型为int。如果这不起作用,请使用minimal reproducible example 创建一个新问题
猜你喜欢
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 2019-12-18
  • 2017-09-20
  • 1970-01-01
  • 2019-11-28
  • 2018-04-25
  • 1970-01-01
相关资源
最近更新 更多