ASP.NET vNext – Identity 3.0 (beta6) in MVC 6 (beta6) Spa – Using Integer Keys Instead of Strings

After looking all over the place and not finding anything specific for Identity 3.0, I got inspired to write this blog post on how to use bigint primary keys for the Identity tables instead of nvarchar(450). The official ASP .Net Identity web site has a good list of resources, but that are mostly 2.0 specific. Also, not much can be inferred from the tests on the aspnet/Identity project on Github,

There is already a blog post written by John Atten on “Extending Identity Models and Using Integer Keys Instead of Strings“, but it is targeted for ASP.NET Identity 2.0 and doesn’t work with ASP.NET Identity 3.0 beta6. Luckily, the steps to enable this scenario in Identity 3.0 are much easier and are finally being documented here.

First, extend the IdentityUser and IdentityRole and explicitly specify a type of long instead of string. For context, if you look at the definition of IdentityUser, you’ll see that it inherits from IdentityUser<string>.

public class ApplicationUser : IdentityUser<long>

public class ApplicationRole : IdentityRole<long>

Next, update your db context to be aware of the user/role and unqiue key changes.

public class ApplicationDbContext: 
    IdentityDbContext<ApplicationUser, ApplicationRole, long>

Next step, in Startup.cs file, ConfigureServices method, make sure the AddIdentity method points to the new user and role types. In addition, make sure the AddEntityFrameworkStores method specifies a long type.

services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext, long>()

At last, in your AccountController, make sure UserManagerSignInManager and RoleManager are bound to the right types.

UserManager<ApplicationUser> userManager;
SignInManager<ApplicationUser> signInManager;
RoleManager<ApplicationRole> rolesManager;

That’s it. If you look at this and the steps you had to follow in Identity 2.0, you’ll be able to easily tell how much the Identity framework architecture has improved in 3.0.