3.1 KiB
title | author | description | keywords | ms.author | manager | ms.date | ms.topic | ms.technology | ms.prod | uid |
---|---|---|---|---|---|---|---|---|---|---|
Configure Identity primary key data type | AdrienTorris | This article outlines the steps for configuring the desired data type used for the ASP.NET Core Identity primary key. | ASP.NET Core,Identity,primary key | scaddie | wpickett | 09/28/2017 | article | aspnet | asp.net-core | security/authentication/identity-primary-key-configuration |
Configure the ASP.NET Core Identity primary key data type
ASP.NET Core Identity allows you to configure the data type used to represent a primary key. Identity uses the string
data type by default. You can override this behavior.
Customize the primary key data type
-
Create a custom implementation of the IdentityUser class. It represents the type to be used for creating user objects. In the following example, the default
string
type is replaced withGuid
.[!code-csharpMain]
-
Create a custom implementation of the IdentityRole class. It represents the type to be used for creating role objects. In the following example, the default
string
type is replaced withGuid
.[!code-csharpMain]
-
Create a custom database context class. It inherits from the Entity Framework database context class used for Identity. The
TUser
andTRole
arguments reference the custom user and role classes created in the previous step, respectively. TheGuid
data type is defined for the primary key.[!code-csharpMain]
-
Register the custom database context class when adding the Identity service in the app's startup class.
ASP.NET Core 2.x
The
AddEntityFrameworkStores
method doesn't accept aTKey
argument as it did in ASP.NET Core 1.x. The primary key's data type is inferred by analyzing theDbContext
object.[!code-csharpMain]
ASP.NET Core 1.x
The
AddEntityFrameworkStores
method accepts aTKey
argument indicating the primary key's data type.[!code-csharpMain]
Test the changes
Upon completion of the configuration changes, the property representing the primary key reflects the new data type. The following example demonstrates accessing the property in an MVC controller.
[!code-csharpMain]