- Home
- ASP.NET Core
- Identity
- Configure the data type of the primary keys using ASP.NET Core Identity
Configure the data type of the primary keys using ASP.NET Core Identity
By default, ASP.NET Core Identity uses the string data type for the primary keys because, as Rick Anderson explained, Microsoft and ASP.NET don't want to get involved in your business logic, that's your concern, so they use the string data type, which is not a strongly-typed data type and allows you to cast it easily.
While this choice by the ASP.NET team is totally understandable, you often need (or just want) a data type other than string for your primary keys, like integers or GUIDs. This is very simple to implement with ASP.NET Core, you have just a few lines of code to write.
-
1
Implement your own classes for the Identity objects (user and role), and specify in the inheritance the data type you want for their primary keys (Guid here)
public class ApplicationUser : IdentityUser<Guid> { } public class ApplicationRole : IdentityRole<Guid> { } -
2
Inherit from the Identity database context and specify which objects you want to use and the data type of their primary keys
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); } } -
3
In your application startup class, add the Identity service, declaring which classes you want to use and the data type of their primary keys, and that's it
public void ConfigureServices(IServiceCollection services) { // ... services.AddIdentity<ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores<ApplicationDbContext, Guid>() .AddDefaultTokenProviders(); // ... }
This implementation doesn't change the data type of the columns in the database, the primary key columns are still NVARCHAR(450) (yes, that's huge), but your objects will be easier to manipulate because you won't have to cast their identifiers every time you use them.
[HttpGet]
public async Task<IActionResult> Test()
{
ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User);
Guid userId = user.Id; // No cast necessary here because user's id property is a Guid, and not a string
throw new NotImplementedException("It's was just to test something very pleasant and very easy to do");
}

