当我尝试向角色添加新用户时出现异常:
ArgumentException:实体类型' IdentityUserRole'使用单个键属性定义,但将2个值传递给' DbSet.Find'方法
这是在下面的行
userManager.AddToRoleAsync(user, "Admin");
这是Startup类中的方法:
private async Task CreateRoles(IServiceProvider serviceProvider) {
//adding custom roles
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>> > ();
var userManager = serviceProvider.GetRequiredService<UserManager<UserEntity>>();
string[] roleNames = { "Admin", "Manager", "User" };
IdentityResult roleResult;
foreach (var roleName in roleNames) {
//creating the roles and seeding them to the database
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist) {
roleResult = await roleManager.CreateAsync(
new IdentityRole<int> {
Name = roleName,
NormalizedName = roleName.ToUpper()
});
}
}
//creating a super user who could maintain the web app
var poweruser = new UserEntity {
UserName = Configuration["AdminUserName"],
Email = Configuration["AdminUserEmail"],
Password = Configuration["AdminUserPassword"],
ResidendceId = int.Parse(Configuration["AdminUserCountryId"])
};
string UserPassword = Configuration["AdminUserPassword"];
UserEntity user = await userManager.FindByEmailAsync(Configuration["AdminUserEmail"]);
if (user == null) {
var createPowerUser = await userManager.CreateAsync(poweruser);
user = poweruser;
}
var adminRoleList = await userManager.GetUsersInRoleAsync("Admin");
if (user != null && !adminRoleList.Any(u => u.Email == user.Email)) {
//here we tie the new user to the "Admin" role
await userManager.AddToRoleAsync(user, "Admin");
}
}
有什么想法吗? 感谢
答案 0 :(得分:1)
在您的DbContext类中添加以下内容
builder.Entity<IdentityUserRole<int>>(b =>
{
b.HasKey(i => new {i.UserId, i.RoleId});
});
这应该为DbFind提供所需的两个键。