.NET Core MinimalAPI EF8中为Identity的UsersRoles实体添加自定义字段
扩展ASP.NET Core Identity用户角色关联表字段解决方案
针对你的需求,无需创建全新自定义表,只需通过扩展原生IdentityUserRole实体并替换Identity默认配置,即可为AspNetUserRoles表添加自定义字段,具体步骤如下:
1. 自定义UserRole实体
创建继承自IdentityUserRole<TKey>的实体,添加所需自定义字段:
public class AppUserRole : IdentityUserRole<string> { // 新增自定义字段 public string CustomField1 { get; set; } public string CustomField2 { get; set; } }
2. 配置DbContext继承关系
修改你的DbContext,使其继承IdentityDbContext时指定自定义的AppUserRole作为用户角色关联实体,并保持原表名不变:
public class AppDbContext : IdentityDbContext< IdentityUser, IdentityRole, string, IdentityUserClaim<string>, AppUserRole, // 替换为自定义的用户角色关联实体 IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // 显式指定表名,确保使用原有的AspNetUserRoles表 builder.Entity<AppUserRole>().ToTable("AspNetUserRoles"); } }
3. 更新Identity服务注册
在Program.cs中注册Identity服务时,指定使用自定义的AppUserRole对应的Store类型:
builder.Services.AddIdentityCore<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders() // 指定自定义UserRole对应的UserStore和RoleStore .AddUserStore<UserStore<IdentityUser, IdentityRole, AppDbContext, string, IdentityUserClaim<string>, AppUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>>() .AddRoleStore<RoleStore<IdentityRole, AppDbContext, string, IdentityRoleClaim<string>, AppUserRole>>();
4. 生成迁移并更新数据库
执行EF Core迁移命令,将字段变更应用到数据库:
Add-Migration AddCustomFieldsToUserRoles Update-Database
完成以上步骤后,原有的AspNetUserRoles表会自动新增CustomField1和CustomField2字段,无需创建新表,完全基于原生Identity框架扩展实现。
内容的提问来源于stack exchange,提问作者stefano
相关产品推荐
相关产品推荐

