Search code examples
asp.net-mvcentity-framework-6.1

Prefix ALL Table Names in EF6


Using MVC5 with EF6, I'm trying to prefix all of an applications table names so that I can place 2 applications into a single database and let them operate completely separately. I need two different sets of users/roles/claims/etc, so I can't use the same AspNet table names that already exist from another app.

After reading through this SO question, I found an answer:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Types().Configure(c => c.ToTable("prefix_" + c.ClrType.Name));
}

This causes errors when using Add-Migration, so I had to add

base.OnModelCreating(modelBuilder);

to my method to quell the errors.

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Types().Configure(c => c.ToTable("prefix_" + c.ClrType.Name));

}

However, whether I add this line, either above or below my type configuration code, the AspNet tables don't change names at all. It's like the type configuration line is being completely ignored.

It changes the name just fine, however, if I do like this:

modelBuilder.Entity<ApplicationUser>().ToTable("SomeFunkyTableName");

That, of course, only changes the AspNetUsers table. I'm not even sure what models to specify to change the others.

My overall goal is to have the following tables, and preferably not have to manually assign them: prefix_AspNetRoles prefix_AspNetUserClaims prefix_AspNetUserLogins prefix_AspNetUserRoles prefix_AspNetUsers

In addition to these, I want all other tables my code-first creates to have the same prefix. How can I accomplish this? Why is my code being ignored?


Solution

  • Instead of prefixing tables why not use a schema?

    You can use the following to set the default schema

    modelBuilder.HasDefaultSchema("MySchema"); // Replace MySchema with the name of your prefix
    

    To set the schema per table you can use

    modelBuilder.Entity<ApplicationUser>().ToTable("SomeFunkyTableName", "MySecondSchema");