求ASP.NET Core 2.0 Identity专属指导:改表名、加属性、主键设为整数
ASP.NET Core 2.0 Identity 自定义配置指引
我太懂这种找不到对应版本教程的烦躁了——ASP.NET Core 2.0的Identity组件和旧版本确实有不少API调整,老资料直接套用肯定行不通。下面就针对你提到的三个核心需求,一步步给你拆解具体实现方式:
1. 将主键改为整数类型
ASP.NET Core 2.0 Identity默认用Guid作为主键,要改成整数的话,需要自定义用户和角色类,继承带泛型参数的基类:
// 自定义用户类,指定主键为int public class AppUser : IdentityUser<int> { // 后续会在这里添加自定义属性 } // 自定义角色类,指定主键为int public class AppRole : IdentityRole<int> { }
然后你的DbContext要继承泛型版本的IdentityDbContext:
public class AppDbContext : IdentityDbContext<AppUser, AppRole, int> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // 表名、属性的自定义配置都写在这个方法里 protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 其他配置代码放这里 } }
最后在Startup.cs的ConfigureServices里,要使用泛型版本的AddIdentity:
services.AddIdentity<AppUser, AppRole>() .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders();
2. 修改Identity默认表名称
默认的Identity表名比如AspNetUsers、AspNetRoles太冗长,我们可以用Fluent API在OnModelCreating里重命名所有相关表:
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 重命名用户表 modelBuilder.Entity<AppUser>().ToTable("Users"); // 重命名角色表 modelBuilder.Entity<AppRole>().ToTable("Roles"); // 重命名用户角色关联表 modelBuilder.Entity<IdentityUserRole<int>>().ToTable("UserRoles"); // 重命名用户声明表 modelBuilder.Entity<IdentityUserClaim<int>>().ToTable("UserClaims"); // 重命名用户登录表 modelBuilder.Entity<IdentityUserLogin<int>>().ToTable("UserLogins"); // 重命名角色声明表 modelBuilder.Entity<IdentityRoleClaim<int>>().ToTable("RoleClaims"); // 重命名用户令牌表 modelBuilder.Entity<IdentityUserToken<int>>().ToTable("UserTokens"); }
3. 添加用户额外属性
直接在自定义的AppUser类里添加你需要的属性就行,比如昵称、生日这些:
public class AppUser : IdentityUser<int> { // 自定义属性示例 public string NickName { get; set; } public DateTime? BirthDate { get; set; } public string Address { get; set; } }
如果需要对属性做额外配置(比如字段长度、是否必填),可以在OnModelCreating里补充:
modelBuilder.Entity<AppUser>(b => { b.Property(u => u.NickName).HasMaxLength(50).IsRequired(false); b.Property(u => u.Address).HasMaxLength(200); });
最后一步:更新数据库
配置完所有内容后,打开Package Manager Console,执行以下命令生成迁移并更新数据库:
Add-Migration CustomIdentityConfig Update-Database
这样就能得到你想要的自定义Identity表结构了,完全适配ASP.NET Core 2.0版本。
内容的提问来源于stack exchange,提问作者Mihto
相关产品推荐
相关产品推荐

