更改 id 列的种子身份用户表?
Posted
技术标签:
【中文标题】更改 id 列的种子身份用户表?【英文标题】:Seed identity user table with changed id column? 【发布时间】:2016-03-19 07:24:37 【问题描述】:我已将 AspNetUser(身份)标签更改为仅具有以下代码的用户。
// Change the name of the table to be Users instead of AspNetUsers
modelBuilder.Entity<IdentityUser>()
.ToTable("Users").Property(p => p.Id).HasColumnName("UserID");
modelBuilder.Entity<ApplicationUser>()
.ToTable("Users").Property(p => p.Id).HasColumnName("UserID");
我的应用程序运行良好,但不是我的种子。我在 Migrations/Configuration.cs 中有这段代码
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
string role = "Admin";
string password = "Password@1234";
//Create Role Admin if it does not exist
if (!RoleManager.RoleExists(role))
var roleresult = RoleManager.Create(new IdentityRole(role));
//Create Admin users with password=123456
var admin1 = new ApplicationUser();
admin1.UserName = "admin1@admin1.com";
admin1.Email = "admin1@admin1.com";
admin1.EmailConfirmed = true;
UserManager.Create(admin1, password);
UserManager.AddToRole(admin1.Id, role);
context.SaveChanges();
我收到错误消息“找不到用户 ID”。好像我的 UserManager.Create 失败了。
如何更改我的种子代码以使用标准 ID 的用户 ID?
【问题讨论】:
【参考方案1】:实际上,当您保存用户时,它还没有给出 id,您必须在创建用户和 addToRole 之间检索用户:
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
string role = "Admin";
string password = "Password@1234";
//Create Role Admin if it does not exist
if (!RoleManager.RoleExists(role))
var roleresult = RoleManager.Create(new IdentityRole(role));
//Create Admin users with password=123456
var admin1 = new ApplicationUser();
admin1.UserName = "admin1@admin1.com";
admin1.Email = "admin1@admin1.com";
admin1.EmailConfirmed = true;
UserManager.Create(admin1, password);
// Refetch user with ID:
dbAdmin1 = context.Users.FirstOrDefault(x => x.UserName == admin1.UserName);
UserManager.AddToRole(dbAdmin1.Id, role);
context.SaveChanges();
【讨论】:
以上是关于更改 id 列的种子身份用户表?的主要内容,如果未能解决你的问题,请参考以下文章