Search code examples
identityguidasp.net-core-identity

problem with Identity when using Guid data type for Id in .net core 6


I am using Identity in .NET Core 6. I would like to have Guid as Id in the User table. So I passed Guid datatype to IdentityUser class in ApplicationUser like this:

public class ApplicationUser:IdentityUser<Guid>
{
    public string FullName { get; set; }
}

This is the configuration class of Identity:

public static IServiceCollection AddIdentityService(this IServiceCollection services, IConfiguration configuration)
{
    var sqlConnection = configuration["ConnectionStrings:SqlConnection"];

    services.AddDbContext<IdentityDataBaseContext>(options => options.UseSqlServer(sqlConnection));
    services.AddScoped<IUserService, UserService>();
    services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<IdentityDataBaseContext>()
            .AddDefaultTokenProviders()
            .AddRoles<ApplicationRole>()
            .AddErrorDescriber<IdentityCustomError>() ;
        
    services.AddScoped<IValidator<CreateUserDto>, CreateUserDtoValidation>();
    services.AddScoped<IValidator<LoginUserDto>, LoginUserDtoValidation>();
        
    services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequiredLength = 8;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = true;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            });
        
    return services;
}

This is the DatabaseContext:

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

When I call FirstOrDefault or First or FirstAsync methods or any other methods for retrieving user data from database, I get this error:

Unable to cast object of type 'System.String' to type 'System.Guid'

This is my AspNetUsers table in SQL Server:

Structure:

AspNetUser Design Table

Sample data:

AspNetUsers table

Any help would be appreciated. Thanks


Solution

  • The Id column of your table AspNetUser must be of type uniqueidentifier (cf. https://learn.microsoft.com/en-us/sql/t-sql/data-types/uniqueidentifier-transact-sql?view=sql-server-ver16), not varchar. It's a specific type to store Guid values.

    Did you create that table manually? Then I suppose you just have to alter your table to change the column type (you may have to empty the table first). Or did you use an EF migration? In that case you might be missing some configuration as EF should have derived the correct column type.

    If this info doesn't really help: I found this short guide to change the Id to an integer (instead of a Guid but similar process): https://www.tektutorialshub.com/asp-net-core/change-primary-key-of-users-table-in-asp-net-core-identity/

    And if that doesn't help: here is the official MS documentation that also explains how to change the Id type (among other customizations): https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-6.0