- 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 string data type for the primary keys, because like Rick Anderson explained, Microsoft and ASP.NET doesn't want to involve in your business logic, this is your concern, so they are using string data type who is not a strong-typed data-type and allows you to cast him easily.
If this choice from ASP.NET's team is totally understandable, you often need (or just want) other data type that 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's objects (user and role), and precise 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 the Identity's database context and precise 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's service, declaring which classes you want to use and the data type of their primary keys, and this is 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 columns of the primary keys are still NVARCHAR(450) (yes, this is huge) but your objects will be more easy to manipulate because you won't have to cast their identifiers every time you'll have to 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");
}