Click here to Skip to main content
12,635,120 members (25,380 online)
Click here to Skip to main content
Add your own
alternative version

Stats

40K views
905 downloads
24 bookmarked
Posted

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

, 1 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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

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.  

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

    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

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

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

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

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)

Share

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#, Asp.net MVC, Entity Framework, NHibernate, SQL Server, IIS, Windows Server.

My personal website: www.byronbd.com

You may also be interested in...

Comments and Discussions

 
QuestionThanks Alot man it's working!! Pin
Member 118466063-Jul-16 4:55
memberMember 118466063-Jul-16 4:55 
QuestionHaving issues in roles Pin
meetjanakiraman13-Jul-15 3:46
membermeetjanakiraman13-Jul-15 3:46 
AnswerRe: Having issues in roles Pin
S. M. Quamruzzaman Rahmani21-Jul-15 21:31
memberS. M. Quamruzzaman Rahmani21-Jul-15 21:31 
BugManageController.cs needs to be updated Pin
loyaltybenefits28-May-15 14:13
memberloyaltybenefits28-May-15 14:13 
GeneralWell Done. Pin
Mahdi K.3-Jan-15 11:10
memberMahdi K.3-Jan-15 11:10 
Questionpermissions management and user groups Pin
dborges28-Dec-14 14:29
memberdborges28-Dec-14 14:29 
Question[resolved] PK int X custom name tables Pin
dborges7-Dec-14 15:08
memberdborges7-Dec-14 15:08 
AnswerRe: PK int X custom name tables Pin
S. M. Quamruzzaman Rahmani8-Dec-14 3:57
memberS. M. Quamruzzaman Rahmani8-Dec-14 3:57 
GeneralRe: PK int X custom name tables Pin
dborges8-Dec-14 4:16
memberdborges8-Dec-14 4:16 
QuestionEntityType 'UserLoginIntPk' has no key defined. Define the key for this EntityType. Pin
Joel Ransom5-Oct-14 15:47
memberJoel Ransom5-Oct-14 15:47 
AnswerRe: EntityType 'UserLoginIntPk' has no key defined. Define the key for this EntityType. Pin
S. M. Quamruzzaman Rahmani2-Nov-14 2:17
memberS. M. Quamruzzaman Rahmani2-Nov-14 2: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 17:31
memberLee Gary11-Sep-14 17: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 20:34
memberS. M. Quamruzzaman Rahmani12-Sep-14 20:34 
GeneralThanks Pin
Luis J. Gutierrez5-Aug-14 10:34
memberLuis J. Gutierrez5-Aug-14 10:34 
Questionthanks Pin
Member 829331826-Jul-14 18:45
memberMember 829331826-Jul-14 18:45 
SuggestionUpdate for Identity 2.0 Samples Project Pin
rnexus3-Jul-14 6:34
memberrnexus3-Jul-14 6:34 
BugThe sample doesn't work Pin
m1dst19-Jun-14 23:29
memberm1dst19-Jun-14 23:29 
GeneralRe: The sample doesn't work Pin
S. M. Quamruzzaman Rahmani20-Jun-14 1:24
memberS. M. Quamruzzaman Rahmani20-Jun-14 1:24 
GeneralMy vote of 5 Pin
Member 102750812-Jun-14 21:59
memberMember 102750812-Jun-14 21:59 
GeneralMy vote of 5 Pin
Md. Rashidul Hasan Masum2-Jun-14 7:54
memberMd. Rashidul Hasan Masum2-Jun-14 7:54 
GeneralMy vote of 5 Pin
Sonali Agarwal1-Jun-14 8:54
memberSonali Agarwal1-Jun-14 8:54 
QuestionInformative and knowledgeable article Pin
Sonali Agarwal1-Jun-14 8:49
memberSonali Agarwal1-Jun-14 8: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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161208.2 | Last Updated 1 Jun 2014
Article Copyright 2014 by S. M. Quamruzzaman Rahmani
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid