Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Improving How ASP.NET Security Tables are Scaffolded

5.00/5 (2 votes)
8 Sep 2017CPOL1 min read 6.5K  
How to improve the naming and change the naming and schema of all the Identity tables like AspNetUsers

Introduction

Have you ever looked at the tables generated for ASP.NET Identity, such as AspNetUser, and thought they didn't quite belong? They ignore your naming conventions. That ugly AspNet... prefix doesn't look right. There are a number of reasons to change the naming of those tables, but the risk and effort are quite high. There are e.g. many foreign key relationships that would be affected by even a single name change.

Using the Code

EF Migrations to the rescue. Migrations has the savvy to drop and recreate all foreign keys before renaming and then put them back again before you know it. I will now show you how to use a migration to rename all those Identity tables and place them in their own schema. I thought “idt” would be a pretty good schema name so I went with that. Please use your own schema or table names, as long as all tables are in the same schema.

To solve this, I looked at the properties of my data context, such as Users, Roles, etc. and found what types were behind those DbSets. I then set table names for each of those types. Simple as that. Oh yes, all the string generic parameters are for the key, and nearly everything Identity has a string key.

All the below code is in the DbContext and written for ASP.NET Core 2, but can very simply be used similarly in earlier versions.

C#
private const string IdentitySchema = "idt";

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaim", IdentitySchema);
    builder.Entity<IdentityRole>().ToTable("Role", IdentitySchema);
    builder.Entity<IdentityUserClaim<string>>().ToTable("UserClaim", IdentitySchema);
    builder.Entity<IdentityUserLogin<string>>().ToTable("UserLogin", IdentitySchema);
    builder.Entity<IdentityUserRole<string>>().ToTable("UserRole", IdentitySchema);
    builder.Entity<ApplicationUser>().ToTable("User", IdentitySchema);
    builder.Entity<IdentityUserToken<string>>().ToTable("UserToken", IdentitySchema);
}

You will have to generate and apply a migration after making these code changes.

License

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