Back to: ASP.NET MVC Tutorial For Beginners and Professionals
Customizing ASP.NET Identity Tables
In this article, I am going to discuss Customizing ASP.NET Identity Tables with Entity Framework Code-First Approach. Please read our previous article where we discussed How to Set up an ASP.NET Identity Database using EF Code-First Approach with both New and Existing Databases.
Customizing ASP.NET Identity Tables
In our previous article, we have seen different approaches to Creating ASP.NET Identity Database using Entity Framework Code-First Approach. So, basically, the ASP.NET Identity with Entity Framework Code First Approach Created the following 6 tables as Part of our ASP.NET Identity Database.
Now, we will see how to customize the above ASP.NET Identity Tables. Let us first add a column to the AspNetUsers table. Currently, if you expand the AspNetUsers table, then you will see the following 12 default columns.
In order to add column(s) in the AspNetUsers table, you need to go to the IdentityModels.cs file and then you need to add the required properties in the ApplicationUser class which you want in the AspNetUsers table. So, modify the AplicationUser class as follows. Here, you can see, we have added three properties i.e. FirstName, LastName, and BirthDate. Also, include the System namespace. Do not remove any existing code from this class. So, your IdentityModels.cs class file should look as shown below with the changes.
using System; using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace AspNetIdentityWithNewProject.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { //Adding New Properties FirstName, LastName, and BirthDate public string FirstName { get; set; } public string LastName { get; set; } public DateTime? BirthDate { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authentication type 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 ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
Now, run the application. Once you run the application, you will get the following Exception.
We are getting the above error as the database was already created and again, we are changing the database using Entity Framework Code First Approach.
How to Solve the above Issue?
As we are going to change the database schema, so we have to Enable Code-First Migrations. Otherwise, we will get the above error.
The Entity Framework introduced automated migration which will process the database migration automatically. That means we do not have to process database migration manually for each change that we made in our domain classes. Here, we will use automated database migration. Apart from Automated Database Migration, we can also use Code-Based Database Migration.
In order to enable the Automated Entity Framework Code-First Database Migrations, go to Tools > NuGet Package Manager > Package Manager Console window as shown in the below image.
Once you open the Package Manager Console window, then run the Enable-Migrations –EnableAutomaticMigration:$true command (make sure that the default project is the project where your context class is located) and press the enter button as shown in the below image.
If the above command is executed successfully, then you will get the following message.
Once the above command is executed successfully in the Package Manager Console window, it creates an internal sealed Configuration class which is derived from DbMigrationConfiguration class in the Migration folder in our project as shown in the below image.
Now, open the Configuration sealed class and you will see the following code. As you can see in the constructor of the Configuration class, AutomaticMigrationsEnabled is set to true.
namespace AspNetIdentityWithNewProject.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<AspNetIdentityWithNewProject.Models.ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; ContextKey = "AspNetIdentityWithNewProject.Models.ApplicationDbContext"; } protected override void Seed(AspNetIdentityWithNewProject.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. } } }
The next step is to set the database initializer in the context class to MigrateDatabaseToLatestVersion. To do so, please modify the ApplicationDbContext class (this class you can find inside the IdentityModels.cs class file which is inside the Models folder) as follows. Do not remove any existing code from the IdentityModels.cs class file.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>()); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
Please include the following namespace as we are using the Configuration class.
using AspNetIdentityWithNewProject.Migrations;
So, we are done with the required setting for Automated Database Migration in Entity Framework Code First Approach. Entity Framework will automatically take care of the migration when we change the domain classes. With the above changes in place, now, run the application and then check the database. Now, you can see, the newly added columns in the AspNetUsers table as shown in the below image.
How to Rename the ASP.NET Identity Table?
In order to rename an ASP.NET Identity table and give it a more relevant name, we need to use the ToTable method in Entity Framework Code First Approach. So, let us rename the AspNetUsers table to User in the database. To do so, we need to override the OnModelCreating method in the ApplicationDbContext class and we need to use the ToTable method to give a different table name for the ApplicationUser Entity as shown in the below image. The argument in the ToTable method is the database table name and the second argument in the ToTable method is the schema name to be used.
Similarly, you can modify all other ASP.NET Identity tables.
With the above method in place, the ApplicationDbContext class should look as follows:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // This needs to go before the other rules! base.OnModelCreating(modelBuilder); //Instead of Writing the Schema in Each ToTable Method we can configure the same //Configure default schema as dbo modelBuilder.HasDefaultSchema("dbo"); //Now Comment the below Statements //modelBuilder.Entity<ApplicationUser>().ToTable("User", "dbo"); //modelBuilder.Entity<IdentityRole>().ToTable("Role", "dbo"); //modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole", "dbo"); //modelBuilder.Entity<IdentityUserClaim>().ToTable("Claim", "dbo"); //modelBuilder.Entity<IdentityUserLogin>().ToTable("Login", "dbo"); //Use the below Statements modelBuilder.Entity<ApplicationUser>().ToTable("User"); modelBuilder.Entity<IdentityRole>().ToTable("Role"); modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole"); modelBuilder.Entity<IdentityUserClaim>().ToTable("Claim"); modelBuilder.Entity<IdentityUserLogin>().ToTable("Login"); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
With the above changes in place, run the application, register a new user, and then verify the database. You should see the database table names are changed as shown in the below image.
How do Rename the Id column of the AspNetUsers Table?
In order to change the column name of the ASP.NET Identity table, we need to use the HasColumnName Fluent API Method. If you see the AspNetUsers Table which we renamed to the User table in the database, then you will see that the Id column is the Primary Key Column as shown in the below image.
Now, we need to change that column Id to the UserId. For this, we need to use the HasColumnName Fluent API Method as shown in the below image.
So, modify the ApplicationDbContext class as follows. Here, apart from the User table, we have replaced all other ASP.NET Identity tables with their original name.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // This needs to go before the other rules! base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>().ToTable("User", "dbo"); modelBuilder.Entity<ApplicationUser>() .Property(u => u.Id) .HasColumnName("UserId"); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
With the above changes in place, run the application, register a new account, and then verify the database and you should see the column UserId as shown in the below image.
For more details about Entity Framework Code First Fluent API Configurations, please read the following three articles.
Fluent API Configurations in Entity Framework
Entity Configurations using Entity Framework Fluent API
Property Configuration using Entity Framework Fluent API
We want to use the default ASP.NET Identity table names. So, remove the OnModelCreating method from the ApplicationDbContext class. At this point, the IdentityModels.cs class file should look as shown below.
using System; using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using AspNetIdentityWithNewProject.Migrations; namespace AspNetIdentityWithNewProject.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { //Adding New Properties FirstName, LastName, and BirthDate public string FirstName { get; set; } public string LastName { get; set; } public DateTime? BirthDate { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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 ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>()); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
Now, run the application, register a new account, and verify the database. The database should look as shown in the below image.
In the next article, I am going to discuss Creating a User Account using ASP.NET Identity. Here, in this article, I try to explain Customizing ASP.NET Identity Tables with EF Code-First Approach. I hope you enjoy this Customizing ASP.NET Identity Tables article.