我正在使用身份验证的应用程序 . 我使用以下框架:
-
ASP.NET Core RC2
-
实体框架核心
-
Npgsql EFCore驱动程序
为了播种,我创建了一个 DataSeeder
类,它在 ConfigureServices
函数中作为Transient Service添加,稍后在Configure函数中调用 . 它检查是否存在 IdentityUser
,如果不存在,则会创建一个名为admin的管理员,并将角色Admin添加到其中 .
但是,在向用户添加角色时,我得到一个异常,说明违反了外键约束,并且ASP_NET_USERS不包含具有该PK的条目 .
我检查了数据库,它确实包含我创建的新角色,但用户表仍然是空的 .
这是我的 DataSeeder
课程:
public class DataSeeder {
private DatabaseContext _context;
private UserManager<IdentityUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
public DataSeeder(DatabaseContext ctx, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager) {
_context = ctx;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task CreateUserAsync() {
if (! await _userManager.Users.AnyAsync()) {
var adminRole = new IdentityRole("admin");
var rootRole = new IdentityRole("root");
await _roleManager.CreateAsync(adminRole);
await _roleManager.CreateAsync(rootRole);
var user = new IdentityUser {
Email = "blabla@example.com",
EmailConfirmed = true,
UserName = "superadmin"
};
await _userManager.CreateAsync(user, "P@SSWORD");
await _userManager.AddClaimAsync(user, new Claim("role", "admin"));
}
}
}
所以异常抛出 AddClaimAsync
. 任何帮助将非常感激
1 回答
检查
_userManager.createAsync
的结果 .您很可能会发现
IdentityUser
上的必需属性丢失或密码无效 .