Asp.Net Core Identity 2.2 和 Identity Server 4,更改用户 ID 类型会导致数据库上下文出错

Asp.Net Core Identity 2.2 and Identity Server 4, Changing User Id type results in an error in the db context

成功从this code sample到运行后,我尝试将Identity User Id类型更改为Guid:

public class AppUser : IdentityUser<Guid>
{
    public string Name { get; set; }
}

我在数据库上下文中遇到错误

public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
    public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : base(options)
    {
    }

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

    }
}

说:

The type 'AuthServer.Infrastructure.Data.Identity.AppUser' cannot be used as type parameter 'TUser' in the generic type or method 'IdentityDbContext'. There is no implicit reference conversion from 'AuthServer.Infrastructure.Data.Identity.AppUser' to 'Microsoft.AspNetCore.Identity.IdentityUser'

猜测此项目中 Identity Server 未使用 Asp.Net 角色,我尝试了一种解决方法,方法是创建一个从 IdentityRole 继承的空 AppRole class 并按如下方式使用它:

public class AppIdentityDbContext : IdentityDbContext<AppUser, AppRole, Guid>

错误停止显示,但在删除迁移文件夹并重新创建新的初始迁移后,出现以下错误:

An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider. Error: GenericArguments1, 'Microsoft.AspNetCore.Identity.IdentityRole', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.

那么可以做什么呢?

您可以尝试以下步骤:

  1. 修改AuthServer.Infrastructure中的AppUser

    public class AppUser : IdentityUser<Guid>
    {
        // Add additional profile data for application users by adding properties to this class
        public string Name { get; set; }        
    }
    
  2. 修改AuthServer.Infrastructure中的AppIdentityDbContext:

    public class AppIdentityDbContext : IdentityDbContext<AppUser, IdentityRole<Guid>, Guid>
    {
            ...
    }
    
  3. 修改AuthServer中的Startup.cs

    services.AddIdentity<AppUser, IdentityRole<Guid>>()
        .AddEntityFrameworkStores<AppIdentityDbContext>()
        .AddDefaultTokenProviders();
    
  4. 重建AuthServer项目,检查是否有错误发生:

    修改RegisterResponseViewModelId = user.Id.ToString();

    修改AccountController.cs:使用user.Id.ToString()代替user.Id

  5. 删除迁移,dotnet ef migrations add InitialCreate,然后再次更新数据库:dotnet ef database update。在命令中选择带有 --context AppIdentityDbContext 的上下文。