覆盖默认身份表名称

4

我想要重命名默认的身份表名称:

  • AspNetRoles(角色)
  • AspNetUserClaims(用户声明)
  • AspNetUserLogins(用户登录)
  • AspNetUserRoles(用户角色)
  • AspNetUsers(用户)

我知道如何使用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");
    }

然而我在使用 EF7 时遇到了困难,因为 DbModelBuilder 已经被 ModelBuilder 替代。有什么建议吗?


你在哪里找到DbModelBuilder已被ModelBuilder替换的信息?我一直没有找到EF6和EF7之间的区别或者相关信息的位置。 - NovaDev
1
请查看ASP.NET 5的GitHub项目。 这是所有开发工作的地方: https://github.com/aspnet/Announcements/labels/Breaking%20change - Reafidy
谢谢!EF团队在Github上开了一个问题,以确保有一个地方记录这些差异:https://github.com/aspnet/EntityFramework.Docs/issues/40。 - NovaDev
5个回答

5

您必须在 SqlServerPropertyBuilder 中使用 ForSqlServer 或 ForRelational 来更改列名,在 modelBuilder 中更改表名。

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

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

更新: 在beta 5版本中,不再强制使用ForSqlServer。

嗨@Pedro,那个看起来是要改变列名,但我想改变表名? - Reafidy
非常相似,您必须使用ForSqlServer modelBuilder.ForSqlServer().Table("Users"),我更新了答案。 - Pedro Fillastre
谢谢,太简单了 - 我昨天肯定盯着屏幕太久了!! - Reafidy
1
除了IdentityUser之外,这个解决方案对于其他Identity*类并不适用。您需要指定显式类,即IdentityUserClaims<string>,而不是IdentityUserClaims来重命名表格。 - Marcin Zablocki

1
下面的代码适用于ASP.NET MVC Core。你可能会问自己为什么要更改默认名称?那么,如果您想在同一数据库上托管多个客户端站点,并具有它们自己的身份验证,以避免与拥有其他数据库相关的额外托管成本,该怎么办呢?记得删除现有的迁移脚本并使用更改进行初始化。希望这可以帮助:
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

    }

1

尝试

    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


0

我想包含一些简化的代码,同时展示如何重命名系统表。用户表应该已经在其模式中命名,但如果必要,可以以相同的方式覆盖。

 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; }
}

}


0

试试这个:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<IdentityUser>(b =>
    { 
        b.ToTable("Users", "dbo"); 
    });

    builder.Entity<IdentityUserClaim<string>>(b =>
    {
        b.ToTable("UserClaims", "dbo");
    });

    builder.Entity<IdentityUserLogin<string>>(b =>
    {
        b.ToTable("UserLogins", "dbo");
    });

    builder.Entity<IdentityUserToken<string>>(b =>
    {
        b.ToTable("UserTokens", "dbo");
    });

    builder.Entity<IdentityRole>(b =>
    {
        b.ToTable("Roles", "dbo");
    });

    builder.Entity<IdentityRoleClaim<string>>(b =>
    {
        b.ToTable("RoleClaims", "dbo");
    });

    builder.Entity<IdentityUserRole<string>>(b =>
    {
        b.ToTable("UserRoles", "dbo");
    });

    base.OnModelCreating(modelBuilder);
}

将此方法添加到ApplicationDbContext类中。

不要忘记添加最后一行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接