为了账号安全,请及时绑定邮箱和手机立即绑定

更改asp.net core 2.2 IdentityUser的Id类型

更改asp.net core 2.2 IdentityUser的Id类型

C#
慕婉清6462132 2022-06-12 11:00:13
我是 dot-net core 2.x 的新手,所以...我想将 asp.net core 2.2 IdentityUser 中的 Id 类型从 string 更改为 int。我通过谷歌(和 stackoverflow 搜索工具)找到的所有示例都为我提供了 asp.net core 2.0 的示例,当您搭建 Identity(2.2 没有提供)时,它提供了一个 ApplicationUser。所以,我不知所措..我尝试的第一件事(我寄予厚望)是:services.AddDefaultIdentity<IdentityUser<int>>()  .AddRoles<IdentityRole>()  .AddDefaultTokenProviders()  .AddEntityFrameworkStores<ApplicationDbContext>();但是,当我尝试添加迁移 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' 类型的约束想法?想法?我可以阅读的文档?
查看完整描述

2 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

要将 IdentityUser 键类型从 string 更改为 int,您还需要将 更改IdentityDbContext为IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>.


启动.cs


services.AddDefaultIdentity<IdentityUser<int>>()

    .AddDefaultUI(UIFramework.Bootstrap4)

    .AddEntityFrameworkStores<ApplicationDbContext>();

ApplicationDbContext


public class ApplicationDbContext : IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>

{

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)

        : base(options)

    {

    }

}

删除Migrations文件夹并删除现有数据库


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


查看完整回答
反对 回复 2022-06-12
?
当年话下

TA贡献1890条经验 获得超9个赞

您可以编写自己的实现,该实现源自IdentityUser


public class AppUser : IdentityUser<int> 

{


}

然后注册它:


services.AddDefaultIdentity<AppUser>()

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


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


查看完整回答
反对 回复 2022-06-12
  • 2 回答
  • 0 关注
  • 161 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号