Click here to Skip to main content
15,881,204 members
Articles / Web Development / ASP.NET

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 99.7K   1.5K   26   23
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.

Introduction

User’s entry tracking is essential for some project. A common example is accounting software. Asp.net 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

<o:p>

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

C#
    //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, 
                               DefaultAuthenticationTypes.ApplicationCookie);

            // 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:

C#
    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. 

C#
//old code 
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
C#
//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

<o:p>

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>

C#
//
// 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

<o:p>

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. 

History

First version: 01 June 2014

License

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


Written By
Product Manager OnnoRokom Software Ltd.
Bangladesh Bangladesh
I am quick in learning new tools and technologies. I am proficient in C#, Asp.net MVC, Entity Framework, NHibernate, SQL Server, IIS, Windows Server.

My personal website: www.byronbd.com

Comments and Discussions

 
QuestionGuid instead of int Pin
Member 1388310222-Jun-18 2:44
Member 1388310222-Jun-18 2:44 
QuestionThanks Alot man it's working!! Pin
Member 118466063-Jul-16 3:55
Member 118466063-Jul-16 3:55 
QuestionHaving issues in roles Pin
meetjanakiraman13-Jul-15 2:46
meetjanakiraman13-Jul-15 2:46 
AnswerRe: Having issues in roles Pin
S. M. Quamruzzaman Rahmani21-Jul-15 20:31
S. M. Quamruzzaman Rahmani21-Jul-15 20:31 
BugManageController.cs needs to be updated Pin
loyaltybenefits28-May-15 13:13
loyaltybenefits28-May-15 13:13 
GeneralWell Done. Pin
Mahdi K.3-Jan-15 10:10
Mahdi 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
S. 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
Joel 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
S. 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
Lee 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
S. M. Quamruzzaman Rahmani12-Sep-14 19:34 
GeneralThanks Pin
Luis J. Gutierrez5-Aug-14 9:34
Luis J. Gutierrez5-Aug-14 9:34 
Questionthanks Pin
Member 829331826-Jul-14 17:45
Member 829331826-Jul-14 17:45 
SuggestionUpdate for Identity 2.0 Samples Project Pin
rnexus3-Jul-14 5:34
rnexus3-Jul-14 5:34 
BugThe sample doesn't work Pin
m1dst19-Jun-14 22:29
m1dst19-Jun-14 22:29 
GeneralRe: The sample doesn't work Pin
S. M. Quamruzzaman Rahmani20-Jun-14 0:24
S. 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 
Very helpful article about new Identity
GeneralMy vote of 5 Pin
Sonali Agarwal1-Jun-14 7:54
Sonali Agarwal1-Jun-14 7:54 
QuestionInformative and knowledgeable article Pin
Sonali Agarwal1-Jun-14 7:49
Sonali 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.