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.


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");
}
16/10/2016
  • ASP.NET Core
  • Identity