Search code examples
intguidasp.net-identity

Identity change GUID to int


How does one change the PK column of the AspNetUser table from a guid to int data type? This should now be possible with the latest asp.net-identity version which got released today.

But I can't find anywhere how this is done?


Solution

  • By default the ASP.NET Identity (using Entity Framework) uses strings as the primary keys, not GUIDs, but it does store GUIDs in those string.

    You need to define a few more classes, I've just created a new project (I'm using the VS2013 Update 2 CTP), here are the identity models you need to change:

    public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
    
    public class ApplicationUserRole : IdentityUserRole<int>
    {
    }
    
    public class ApplicationUserLogin : IdentityUserLogin<int>
    {
    }
    
    public class ApplicationUserClaim : IdentityUserClaim<int>
    {
    }
    
    public class ApplicationRole : IdentityRole<int, ApplicationUserRole>
    {
    }
    
    public class ApplicatonUserStore :
        UserStore<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public ApplicatonUserStore(ApplicationDbContext context)
            : base(context)
        {
        }
    }
    
    public class ApplicationDbContext
        : IdentityDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }
    

    You'll also need to update a few other places, just follow the compile errors, the most common change will be the need to convert the string returned form User.Identity.GetUserId() to an integer.

    Also, In answering another question (I did ask the question though), I've provided an example solution that does just this, see the repository below:

    https://github.com/JSkimming/AspNet.Identity.EntityFramework.Multitenant