Override Default Identity Table Names

南楼画角 提交于 2019-12-01 04:48:27

问题


I would like to rename the default identity table names:

  • AspNetRoles
  • AspNetUserClaims
  • AspNetUserLogins
  • AspNetUserRoles
  • AspNetUsers

I understand how to do this using EF6:

 protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>()
            .ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
        modelBuilder.Entity<User>()
            .ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
    }

However I'm struggling with EF7 as the DbModelBuilder has been replaced with ModelBuilder. Any suggestions?


回答1:


You must use ForSqlServer or ForRelational in the SqlServerPropertyBuilder to change the column name and in the modelBuilder to change the table name

modelBuilder.Entity<IdentityUser>()
                .Property(o => o.Id)
                .ForSqlServer()
                .Column("User_Id")

 modelBuilder.Entity<IdentityUser>()
                    .ForSqlServer()
                    .Table("User")

Update : For the beta 5 is not longer mandatory to use ForSqlServer




回答2:


The following code works for ASP.NET MVC Core. You may ask yourself why you would want to change the default names? Well, what if you wanted to host several client sites, with their own authentication, on the same database to avoid additional hosting costs associated with having additional databases. Remember to delete the existing migration scripts and initialise with the changes. Hope this helps:

protected override void OnModelCreating(ModelBuilder builder)
    {
        const string

          IDENTITY_PREFIX = "CLIENT9002",


          ASP_NET_USERS = "T0001_Security_User",
          ASP_NET_ROLES = "T0002_Security_Role",
          ASP_NET_USER_ROLES = "T0003_Security_User_Role",
          ASP_NET_USER_LOGIN = "T0004_Security_User_Login",
          ASP_NET_USER_CLAIM = "T0005_Security_User_Claim",
          ASP_NET_ROLE_CLAIM = "T0006_Security_Role_Claim",

          ASP_NET_USER_TOKENS = "T0007_AspNetUserTokens"
          ;

        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        #region Change Identity Tables

        #region User
        //aside:    The PK and FK need to be renamed in the DB to avoid conflict.
        //          Also any migration scripts in future also have to be stripped of any reference to Identity Tables
        builder.Entity<ApplicationUser>(entity =>
        {

            entity.HasKey(e => e.Id).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_USERS));
            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USERS)).Property(p => p.Id).HasColumnName("UserId");

            entity.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.UserId).IsRequired().HasConstraintName(string.Format("{0}_FK_{1}_{2}", IDENTITY_PREFIX, ASP_NET_USERS, "Claims"));
            entity.HasMany(r => r.Logins).WithOne().HasForeignKey(rc => rc.UserId).IsRequired().HasConstraintName(string.Format("{0}_FK_{1}_{2}", IDENTITY_PREFIX, ASP_NET_USERS, "Logins"));
            entity.HasMany(r => r.Roles).WithOne().HasForeignKey(rc => rc.UserId).IsRequired().HasConstraintName(string.Format("{0}_FK_{1}_{2}", IDENTITY_PREFIX, ASP_NET_USERS, "Roles"));

            entity.HasMany(d => d.recipecreatedby).WithOne(p => p.ApplicationUserCreatedBy).HasForeignKey(d => d.createdby); //.IsRequired();
            entity.HasMany(d => d.recipechangedby).WithOne(p => p.ApplicationUserChangedBy).HasForeignKey(d => d.changedby);

            entity.HasIndex(e => e.NormalizedEmail).HasName(string.Format("{0}_{1}_{2}", IDENTITY_PREFIX, ASP_NET_USERS, "EmailIndex"));
            entity.HasIndex(e => e.NormalizedUserName).HasName(string.Format("{0}_{1}_{2}", IDENTITY_PREFIX, ASP_NET_USERS, "UserNameIndex"));

        }
            );
        #endregion

        #region Role
        builder.Entity<ApplicationRole>(entity =>
        {
            entity.HasKey(e => e.Id).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_ROLES));
            entity.HasIndex(e => e.NormalizedName).HasName(string.Format("{0}_{1}_{2}", IDENTITY_PREFIX, ASP_NET_ROLES, "RoleNameIndex"));
            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_ROLES));
            entity.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired().HasConstraintName(string.Format("{0}_FK_{1}_{2}", IDENTITY_PREFIX, ASP_NET_ROLES, "Claims"));
            entity.HasMany(r => r.Users).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired().HasConstraintName(string.Format("{0}_FK_{1}_{2}", IDENTITY_PREFIX, ASP_NET_ROLES, "Users"));
        }
        );
        #endregion

        #region Role Claims            
        builder.Entity<IdentityRoleClaim<int>>(entity =>
        {
            entity.HasKey(e => e.Id).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_ROLE_CLAIM));
            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_ROLE_CLAIM));
        }
        );
        #endregion

        #region User Claims
        builder.Entity<IdentityUserClaim<int>>(entity =>
        {
            entity.HasKey(e => e.Id).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_USER_CLAIM));
            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_CLAIM));
        }
        );
        #endregion

        #region User Login
        builder.Entity<IdentityUserLogin<int>>(entity =>
        {
            entity.HasKey(e => new { e.LoginProvider, e.ProviderKey }).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_USER_LOGIN)); ;
            entity.Property(e => e.LoginProvider).HasMaxLength(450);

            entity.Property(e => e.ProviderKey).HasMaxLength(450);
            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_LOGIN));

        });
        #endregion

        #region User Role
        builder.Entity<IdentityUserRole<int>>(entity =>
        {
            entity.HasKey(e => new { e.UserId, e.RoleId }).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_USER_ROLES));
            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_ROLES));
        });
        #endregion


        #region Tokens

            builder.Entity<IdentityUserToken<int>>(entity =>
            {
                entity.HasKey(e => new { e.UserId, e.LoginProvider, e.Name }).HasName(string.Format("{0}_PK_{1}", IDENTITY_PREFIX, ASP_NET_USER_TOKENS));
                entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_TOKENS));
            });
        #endregion

        #region Recipes
        builder.Entity<recipe>(x =>
        {
            x.HasKey(t => new { t.recipeid });
            x.HasIndex(i => new { i.slugid });
            x.HasIndex(i => new { i.name });
      //      x.HasMany(r => r.Ingredients).WithOne().HasForeignKey(rc => rc.RecipeID).IsRequired();
        });

      //  builder.Entity<Ingredients>().HasKey(t => new { t.IngredientID });

        #endregion

        #endregion

    }



回答3:


Try

    builder.Entity<ApplicationUser>().ToTable("User");
    builder.Entity<ApplicationRole>().ToTable("Role");

    builder.Entity<IdentityUserRole<string>>().ToTable("UserRole");
    builder.Entity<IdentityUserClaim<string>>().ToTable("UserClaim");
    builder.Entity<IdentityUserLogin<string>>().ToTable("UserLogin");

    builder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaim");
    builder.Entity<IdentityUserToken<string>>().ToTable("UserToken");

@noelbr




回答4:


I thought I'd include some code (streamlined) that also shows how to rename the system tables. User Tables should already be named in their schema but can be overwritten the same way if necessary

 using Bhail.Models;
using Bhail.Models.Issues;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using OpenIddict.Models;

 namespace Bhail.Data
  {
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
    #region Custom/Additional Tables Created
    public DbSet<Issue> Issue { get; set; }
    public DbSet<IssueAttachments> IssueAttachments { get; set; }
    public DbSet<IssueNotes> IssueNotes { get; set; }
    //        public DbSet<IssueLeaseConditionAssignment> IssueLeaseAssignment { get; set; }
    //public DbSet<IssuePriorityType> IssuePriorityType { get; set; }
    public DbSet<IssueType> IssueType { get; set; }
    //public DbSet<Status> Status { get; set; }
    public DbSet<Lease> Lease { get; set; }
    public DbSet<LeaseCondition> LeaseCondition { get; set; }
    public DbSet<Property> Property { get; set; }
    public DbSet<PropertyUserAssignment> PropertyUserAssignment { get; set; }
    #endregion

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        const string

          IDENTITY_PREFIX = "CLIENT1000",

          ASP_NET_USER = "T0001_SECURITY_USER",
          ASP_NET_ROLE = "T0002_SECURITY_ROLE",
          ASP_NET_USER_ROLE = "T0003_SECURITY_USER_ROLE",
          ASP_NET_USER_LOGIN = "T0004_SECURITY_USER_LOGIN",
          ASP_NET_USER_CLAIM = "T0005_SECURITY_USER_CLAIM",
          ASP_NET_ROLE_CLAIM = "T0006_SECURITY_ROLE_CLAIM",
          ASP_NET_USER_TOKEN = "T0007_SECURITY_USER_TOKENS",
          OPENIDDICT_AUTHORIZATION = "T0010_SECURITY_OPENIDDICT_AUTHORIZATION",
          OPENIDDICT_APPLICATION = "T0011_SECURITY_OPENIDDICT_APPLICATION",
          OPENIDDICT_SCOPE = "T0012_SECURITY_OPENIDDICT_SCOPE",
          OPENIDDICT_TOKEN = "T0013_SECURITY_OPENIDDICT_TOKEN"
          ;

        #region Security
        #region Identity Tables
        base.OnModelCreating(modelBuilder);
        // Add your customizations after calling base.OnModelCreating(modelBuilder);

        // Need to add the FK for the INHERITED AUDIT which is different as different tables
        modelBuilder.Entity<ApplicationUser>(entity =>
        {

            entity.ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER));
            entity.HasMany(d => d.issueattachmentcreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby); //.IsRequired();
            entity.HasMany(d => d.issueattachmentchangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            entity.HasMany(d => d.issuecreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.issuechangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            ////#region Additional User Assignment other than Audit
            entity.HasMany(d => d.issueinspectedby).WithOne(p => p.issueinspectedby).HasForeignKey(d => d.inspectedby);
            entity.HasMany(d => d.issuecompletedby).WithOne(p => p.issuecompletedby).HasForeignKey(d => d.completedby);
            ////#endregion

            entity.HasMany(d => d.issuenotescreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.issuenoteschangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            //entity.HasMany(d => d.prioritytypecreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            //entity.HasMany(d => d.prioritytypechangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            entity.HasMany(d => d.issuetypecreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.issuetypechangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            //entity.HasMany(d => d.statuscreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            //entity.HasMany(d => d.statuschangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            entity.HasMany(d => d.leaseconditioncreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.leaseconditionchangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            entity.HasMany(d => d.propertycreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.propertychangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            entity.HasMany(d => d.issueleaseconditionassignmentcreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.issueleaseconditionassignmentchangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);

            entity.HasMany(d => d.propertyuserassignmentcreatedby).WithOne(p => p.applicationusercreatedby).HasForeignKey(d => d.createdby);
            entity.HasMany(d => d.propertyuserassignmentchangedby).WithOne(p => p.applicationuserchangedby).HasForeignKey(d => d.changedby);



            #region Property User Assignment
            //NB: doesnt seem necessary as already defined within the table
            //entity.HasMany(d => d.propertyuserassignment).WithOne(p => p.ApplicationUser).HasForeignKey(d => d.userassignment);
            #endregion

        });

        modelBuilder.Entity<ApplicationRole>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_ROLE));
        modelBuilder.Entity<IdentityUserClaim<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_CLAIM));
        modelBuilder.Entity<IdentityUserRole<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_ROLE));
        modelBuilder.Entity<IdentityUserLogin<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_LOGIN));
        modelBuilder.Entity<IdentityRoleClaim<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_ROLE_CLAIM));
        modelBuilder.Entity<IdentityUserToken<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, ASP_NET_USER_TOKEN));
        #endregion

        #region OpenIDDict
        modelBuilder.Entity<OpenIddictApplication<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, OPENIDDICT_APPLICATION));
        modelBuilder.Entity<OpenIddictAuthorization<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, OPENIDDICT_AUTHORIZATION));
        modelBuilder.Entity<OpenIddictScope<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, OPENIDDICT_SCOPE));
        modelBuilder.Entity<OpenIddictToken<int>>().ToTable(string.Format("{0}_{1}", IDENTITY_PREFIX, OPENIDDICT_TOKEN));
        #endregion
        #endregion

        #region Issues
        modelBuilder.Entity<IssueLeaseConditionAssignment>().HasKey(t => new { t.issueid, t.leaseconditionid });
        modelBuilder.Entity<PropertyUserAssignment>().HasKey(t => new { t.propertyid, t.userassignment });


        #region Additional Indexes

        //aside: as checks are done on whetherh title exists, create an index for these.
        modelBuilder.Entity<Issue>().HasIndex(e => e.statusid);
        modelBuilder.Entity<Issue>().HasIndex(e => e.title);
        modelBuilder.Entity<Issue>().HasIndex(e => e.completed);
        modelBuilder.Entity<Issue>().HasIndex(e => e.prioritytypeid);
        modelBuilder.Entity<Issue>().HasIndex(e => e.issuetypeid);

        modelBuilder.Entity<Property>().HasIndex(e => e.statusid);
        modelBuilder.Entity<Property>().HasIndex(e => e.title);

        modelBuilder.Entity<Lease>().HasIndex(e => e.statusid);
        modelBuilder.Entity<Lease>().HasIndex(e => e.title);
        modelBuilder.Entity<Lease>().HasIndex(e => e.propertyid);

        modelBuilder.Entity<LeaseCondition>().HasIndex(e => e.leaseid);
        modelBuilder.Entity<LeaseCondition>().HasIndex(e => e.title);

        //modelBuilder.Entity<Status>().HasIndex(e => e.title);
        //modelBuilder.Entity<Status>().HasIndex(e => e.standard);

        modelBuilder.Entity<IssueNotes>().HasIndex(e => e.title);

        modelBuilder.Entity<IssueAttachments>().HasIndex(e => e.title);
        modelBuilder.Entity<IssueAttachments>().HasIndex(e => e.attachmenttype);
        //modelBuilder.Entity<IssuePriorityType>().HasIndex(e => e.title);
        modelBuilder.Entity<IssueType>().HasIndex(e => e.title);

        #endregion


        #endregion
    }

    public DbSet<ApplicationUser> ApplicationUser { get; set; }
}

}



来源:https://stackoverflow.com/questions/31084416/override-default-identity-table-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!