我尝试使用默认管理员用户和 3 个角色为我的数据库添加种子。我在 Program.cs 文件中执行此操作。代码如下:
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var roles = new[] { "Admin", "Manager", "User" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
IdentityRole roleRole = new IdentityRole(role);
await roleManager.CreateAsync(roleRole);
}
}
}
using (var scope = app.Services.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string email = "[email protected]";
string password = "Pa$$word!";
if (await userManager.FindByNameAsync(email) == null)
{
var user = new ApplicationUser();
user.FirstName = "System";
user.LastName = "Administrator";
user.Email = email;
user.UserName = email;
await userManager.CreateAsync(user, password);
await userManager.AddToRoleAsync(user, "Admin");
}
}
当我运行应用程序并到达将用户添加到管理员角色的行时,我收到一条错误消息:
SqlException:INSERT 语句与 FOREIGN KEY 约束“FK_AspNetUserRoles_AspNetUsers_UserId”冲突。冲突发生在数据库“MapTest”、表“dbo.AspNetUsers”、列“Id”中。 该声明已终止。
这是初始迁移后的新应用程序。我已经使用 .Net 7 完成了此任务,但在 .Net 8 中遇到了这个问题。我似乎找不到任何有关此问题的信息,或者我是否做错了什么。
有什么想法吗?
your text
这里的主要问题是用户管理器不是创建用户。原因是密码无效,没有数字。将
var result =
添加到 await userManager.CreateAsync(user, password);
会使这一点更加明显。
您还应该调用 EmailStore 的方法来设置电子邮件。这会初始化模型中的标准化搜索属性。
using (var scope = app.Services.CreateScope())
{
string email = "[email protected]";
string password = "Pass123$";
var roles = new[] { "Admin", "Manager", "User" };
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var userStore = scope.ServiceProvider.GetRequiredService<IUserStore<ApplicationUser>>();
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
IdentityRole roleRole = new IdentityRole(role);
await roleManager.CreateAsync(roleRole);
}
}
if (await userManager.FindByNameAsync(email) == null)
{
var user = new ApplicationUser();
user.Email = email;
user.UserName = email;
user.EmailConfirmed = true;
var emailStore = GetEmailStore();
await emailStore.SetEmailAsync(user, email, CancellationToken.None);
var result = await userManager.CreateAsync(user, password);
await userManager.AddToRoleAsync(user, "Admin");
}
IUserEmailStore<ApplicationUser> GetEmailStore()
{
if (!userManager.SupportsUserEmail)
{
throw new NotSupportedException("The default UI requires a user store with email support.");
}
return (IUserEmailStore<ApplicationUser>)userStore;
}
}