Search code examples
c#asp.net-coreentity-framework-coreasp.net-identityidentityserver4

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


After got this code sample to run successfully, I tried to change the Identity User Id type to Guid:

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

I got error in the database context

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

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

    }
}

saying:

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'

Guessing that Asp.Net Roles are not used by Identity Server in this project, I've tried a workaround by creating an empty AppRole class inheriting from IdentityRole and used it as follows:

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

Error stopped showing but after deleted migrations folder and recreated a new initial migration, I've got the following error:

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'.

So what can be done ?


Solution

  • You can try below steps :

    1. Modify the AppUser in AuthServer.Infrastructure :

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

      public class AppIdentityDbContext : IdentityDbContext<AppUser, IdentityRole<Guid>, Guid>
      {
              ...
      }
      
    3. Modify the Startup.cs in AuthServer :

      services.AddIdentity<AppUser, IdentityRole<Guid>>()
          .AddEntityFrameworkStores<AppIdentityDbContext>()
          .AddDefaultTokenProviders();
      
    4. Rebuild the AuthServer project, check whether any error occurs :

      Modify RegisterResponseViewModel: Id = user.Id.ToString();

      Modify AccountController.cs: use user.Id.ToString() instead of user.Id

    5. Delete the Migrations , dotnet ef migrations add InitialCreate , and then again update database : dotnet ef database update . Choose which context with --context AppIdentityDbContext in the command .