Click here to Skip to main content
15,389,584 members
Articles / Web Development / ASP.NET
Posted 1 Jun 2014


26 bookmarked

ASP.NET Identity 2.0 Change Primary Key from String to Integer

Rate me:
Please Sign up or sign in to vote.
5.00/5 (14 votes)
1 Jun 2014CPOL3 min read
ASP.NET team released Identity framework 2.0. The new release contain some new features like generic primary key. This article explain how to change primary key from string to integer & use it with MVC5.


User’s entry tracking is essential for some project. A common example is accounting software. identity framework 1.0 use string (128 char) as userId. If an application work with huge amount of data then retrieve information with user’s info may slow because of string matching. In that case Integer is the best solution.

Latest Identity framework 2.0 comes with some new features. One of them is generic primary key. So now, we can make primary key integer or whatever we like. Identity 2.0 included in Visual Studio 2013 update 2 (released May 12, 2014).

Using the code

In this article we are going to change primary key data type from string to int with bellow steps<o:p>

Create a MVC project using Visual Studio 2013 update 2

Image 1

Lets create a new ASP.Net web application named Identity2IntPK using Visual Studio 2013. Next select MVC with Individual User Account.

Image 2

Visual Studio 2013 MVC template will create a structure like this image. 

IdentityConfig file contain a class ApplicationUserManager where we can set password strength.

Startup.Auth contain a partial class Startup. Here we can set 3rd party login provider like facebook, google etc.

IdentityModels contain ApplicationUser & ApplicationDbContext. Basically we are going to change this file. 

AccountViewModels contain some classes uses for data transfer & validation.

AccountController has only AccountController class which responsible for login, registration, password reset & others.

Account this folder contain some view files such as Login.cshtml, Register.cshtml, ResetPassword.cshtml. 



Create & change Identity classes

We have to change bellow files to finish this task.

  1. IdentityModels.cs
  2. IdentityConfig.cs
  3. Startup.Auth.cs


1. IdentityModels.cs : Open file form Modules folder & add UserRoleIntPk, UserClaimIntPk, UserLoginIntPk, RoleIntPk, UserStoreIntPk, RoleStoreIntPk classes.  

    //New drived classes 
    public class UserRoleIntPk : IdentityUserRole<int>

    public class UserClaimIntPk : IdentityUserClaim<int>

    public class UserLoginIntPk : IdentityUserLogin<int>

    public class RoleIntPk : IdentityRole<int, UserRoleIntPk>
        public RoleIntPk() { }
        public RoleIntPk(string name) { Name = name; }

    public class UserStoreIntPk : UserStore<ApplicationUser, RoleIntPk, int, 
        UserLoginIntPk, UserRoleIntPk, UserClaimIntPk>
        public UserStoreIntPk(ApplicationDbContext context)
            : base(context)

    public class RoleStoreIntPk : RoleStore<RoleIntPk, int, UserRoleIntPk>
        public RoleStoreIntPk(ApplicationDbContext context)
            : base(context)

Also change ApplicationUser & ApplicationDbContext in same file.

    //change bellow classes
    public class ApplicationUser : IdentityUser<int, UserLoginIntPk, UserRoleIntPk, UserClaimIntPk>
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
            var userIdentity = await manager.CreateIdentityAsync(this, 

            // Add custom user claims here
            return userIdentity;

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, RoleIntPk, int, 
        UserLoginIntPk, UserRoleIntPk, UserClaimIntPk>
        public ApplicationDbContext()
            : base("DefaultConnection")

        public static ApplicationDbContext Create()
            return new ApplicationDbContext();


2. IdentityConfig.cs: Open this file from App_Start folder & change ApplicationUserManager class. After change ApplicationUserManager will looks like:

    public class ApplicationUserManager : UserManager<ApplicationUser, int>
        public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
            : base(store)

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, 
            IOwinContext context) 
            var manager = new ApplicationUserManager(new UserStoreIntPk(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
                RequiredLength = 6,
                //RequireNonLetterOrDigit = true,
                //RequireDigit = true,
                //RequireLowercase = true,
                //RequireUppercase = true,
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser, int>
                MessageFormat = "Your security code is: {0}"
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser, int>
                Subject = "Security Code",
                BodyFormat = "Your security code is: {0}"
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
                manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>
                                            (dataProtectionProvider.Create("ASP.NET Identity"));
            return manager;

Here we replace <ApplicationUserwith <ApplicationUser, int>


3. Startup.Auth.cs: Open this file from App_Start folder & change old code with new code. 

//old code 
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
//New code 
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>
         validateInterval: TimeSpan.FromMinutes(30),
         regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
         getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))

Change account controller to work with new primary key


Our work is almost done. If you compile your code you get almost 16 errors & all are in AccountController.cs file. So we have to change this file to work with new system.

Open AccountController.cs & change all userId type from string to int. Then replace all User.Identity.GetUserId() with int.Parse(User.Identity.GetUserId()) except LinkLogin function.

Also LinkLoginCallback change to <o:p>

// GET: /Account/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
    if (loginInfo == null)
        return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
    IdentityResult result = await UserManager.AddLoginAsync(int.Parse(User.Identity.GetUserId()), loginInfo.Login);
    if (result.Succeeded)
        return RedirectToAction("Manage");
    return RedirectToAction("Manage", new { Message = ManageMessageId.Error });

Running the Application

Now compile your project & if everything is fine then run it. Click register from navigation menu & add an user. 

Image 3


Entity framework will create a database for you with AspNet authorization tables. If you like to check what happened in database then open DefaultConnection from server explorer. right click on AspNetUsers table & select open table definition, you will see id is now int instead of string.

<o:p>Image 4

Points of Interest

Identity 2 is great because it comes with a lot of useful things. But default identity system may not all time compatible with all application. That is why this article may helpful for those who want more extensibility. 


First version: 01 June 2014


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

S. M. Quamruzzaman Rahmani
Product Manager OnnoRokom Software Ltd.
Bangladesh Bangladesh
I am quick in learning new tools and technologies. I am proficient in C#, MVC, Entity Framework, NHibernate, SQL Server, IIS, Windows Server.

My personal website:

Comments and Discussions

QuestionGuid instead of int Pin
Member 1388310222-Jun-18 2:44
MemberMember 1388310222-Jun-18 2:44 
QuestionThanks Alot man it's working!! Pin
Member 118466063-Jul-16 3:55
MemberMember 118466063-Jul-16 3:55 
QuestionHaving issues in roles Pin
meetjanakiraman13-Jul-15 2:46
Membermeetjanakiraman13-Jul-15 2:46 
AnswerRe: Having issues in roles Pin
S. M. Quamruzzaman Rahmani21-Jul-15 20:31
MemberS. M. Quamruzzaman Rahmani21-Jul-15 20:31 
BugManageController.cs needs to be updated Pin
loyaltybenefits28-May-15 13:13
Memberloyaltybenefits28-May-15 13:13 
GeneralWell Done. Pin
Mahdi K.3-Jan-15 10:10
MemberMahdi K.3-Jan-15 10:10 
Questionpermissions management and user groups Pin
diegobdev28-Dec-14 13:29
professionaldiegobdev28-Dec-14 13:29 
Question[resolved] PK int X custom name tables Pin
diegobdev7-Dec-14 14:08
professionaldiegobdev7-Dec-14 14:08 
AnswerRe: PK int X custom name tables Pin
S. M. Quamruzzaman Rahmani8-Dec-14 2:57
MemberS. M. Quamruzzaman Rahmani8-Dec-14 2:57 
GeneralRe: PK int X custom name tables Pin
diegobdev8-Dec-14 3:16
professionaldiegobdev8-Dec-14 3:16 
QuestionEntityType 'UserLoginIntPk' has no key defined. Define the key for this EntityType. Pin
Joel Ransom5-Oct-14 14:47
MemberJoel Ransom5-Oct-14 14:47 
AnswerRe: EntityType 'UserLoginIntPk' has no key defined. Define the key for this EntityType. Pin
S. M. Quamruzzaman Rahmani2-Nov-14 1:17
MemberS. M. Quamruzzaman Rahmani2-Nov-14 1:17 
QuestionCannot insert the value NULL into column 'Id', table 'dbo.AspNetUsers'; column does not allow nulls. INSERT fails. The statement has been terminated. Pin
Lee Gary11-Sep-14 16:31
MemberLee Gary11-Sep-14 16:31 
AnswerRe: Cannot insert the value NULL into column 'Id', table 'dbo.AspNetUsers'; column does not allow nulls. INSERT fails. The statement has been terminated. Pin
S. M. Quamruzzaman Rahmani12-Sep-14 19:34
MemberS. M. Quamruzzaman Rahmani12-Sep-14 19:34 
GeneralThanks Pin
Luis J. Gutierrez5-Aug-14 9:34
MemberLuis J. Gutierrez5-Aug-14 9:34 
Questionthanks Pin
Member 829331826-Jul-14 17:45
MemberMember 829331826-Jul-14 17:45 
SuggestionUpdate for Identity 2.0 Samples Project Pin
rnexus3-Jul-14 5:34
Memberrnexus3-Jul-14 5:34 
BugThe sample doesn't work Pin
m1dst19-Jun-14 22:29
Memberm1dst19-Jun-14 22:29 
GeneralRe: The sample doesn't work Pin
S. M. Quamruzzaman Rahmani20-Jun-14 0:24
MemberS. M. Quamruzzaman Rahmani20-Jun-14 0:24 
GeneralMy vote of 5 Pin
Taskin Khaleque2-Jun-14 20:59
professionalTaskin Khaleque2-Jun-14 20:59 
GeneralMy vote of 5 Pin
Md. Rashidul Hasan Masum2-Jun-14 6:54
professionalMd. Rashidul Hasan Masum2-Jun-14 6:54 
GeneralMy vote of 5 Pin
Sonali Agarwal1-Jun-14 7:54
MemberSonali Agarwal1-Jun-14 7:54 
QuestionInformative and knowledgeable article Pin
Sonali Agarwal1-Jun-14 7:49
MemberSonali Agarwal1-Jun-14 7:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.