核心 3.1 MVC 中的种子数据库 AspNetUserRoles 表 ASP.NET



我是初学者,我正在研究 Asp.Net Core 3 MVC。我正在尝试播种AspNetUserRoles表。用户和角色工作正常,并且种子设定没有错误,但 AspNetUserRoles 表为空。我创建了这样的种子类:

public class SeedData
{
private AppIdentityDbContext _context;
public SeedData(AppIdentityDbContext context)
{
_context = context;
}
public async void Initialize()
{
var user = new ApplicationUser
{
UserName = "progmd@mail.ru",
NormalizedUserName = "progmd@mail.ru",
Email = "progmd@mail.ru",
NormalizedEmail = "progmd@mail.ru",
City = "SuperAdmin",
EmailConfirmed = true,
LockoutEnabled = false,
SecurityStamp = Guid.NewGuid().ToString()
};
var roleStore = new RoleStore<IdentityRole>(_context);
if (!_context.Roles.Any(r => r.Name == "admin"))
{
await roleStore.CreateAsync(new IdentityRole { Id = "b562e963-6e7e-4f42-9339-1235b1234qw5", Name = "admin", NormalizedName = "admin" });
}
if (!_context.Users.Any(u => u.UserName == user.UserName))
{
var password = new PasswordHasher<ApplicationUser>();
var hashed = password.HashPassword(user, "111111Test");
user.PasswordHash = hashed;
var userStore = new UserStore<ApplicationUser>(_context);
await userStore.CreateAsync(user);
await userStore.AddToRoleAsync(user, "admin");
}
IdentityUserRole<string> ur = new IdentityUserRole<string>();
ur.RoleId = "b562e963-6e7e-4f42-9339-1235b1234qw5";
ur.UserId = user.Id;
//await _context.UserRoles.AddAsync(ur);
await _context.SaveChangesAsync();
}
}  

我该如何解决这个问题?

好的,我找到了另一种方法。我删除了类 SeedData,并在 AppIdentityDbContext 中添加了此代码.cs

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<IdentityRole>().HasData(new List<IdentityRole>
{
new IdentityRole
{
Id = "1",
Name = "admin",
NormalizedName = "ADMIN"
}
});
var hasher = new PasswordHasher<ApplicationUser>();
builder.Entity<ApplicationUser>().HasData(new ApplicationUser
{
Id = "1",
UserName = "progmd@mail.ru",
NormalizedUserName = "progmd@mail.ru",
Email = "progmd@mail.ru",
NormalizedEmail = "progmd@mail.ru",
City = "SuperAdmin",
EmailConfirmed = true,
LockoutEnabled = false,
PasswordHash = hasher.HashPassword(null, "111111Test"),
});
builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
{
RoleId = "1",
UserId = "1"
});
}

请记住添加迁移并更新数据库。

PS 感谢马克·迪尼尔·维森特!

相关内容

  • 没有找到相关文章