Reputation: 21
I get an Exception when I try to add a new user to a role:
ArgumentException: Entity type 'IdentityUserRole' is defined with a single key property, but 2 values were passed to the 'DbSet.Find' method.
This was thrown at the line below
userManager.AddToRoleAsync(user, "Admin");
This is the method in Startup class:
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");
}
}
Any idea? Thanks
Upvotes: 1
Views: 1222
Reputation: 11
Please Use from string instead of int--->
builder.Entity<IdentityUserRole<string>>(b =>
{
b.HasKey(i => new {i.UserId, i.RoleId});
});
Upvotes: 1
Reputation: 950
In your DbContext class add the following
builder.Entity<IdentityUserRole<int>>(b =>
{
b.HasKey(i => new {i.UserId, i.RoleId});
});
This should give DbFind the two keys that it is looking for.
Upvotes: 2