简体   繁体   中英

ASP.NET CORE 2 - Entity type 'IdentityUserRole<int>' is defined with a single key property, but 2 values were passed to the 'DbSet.Find' method

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

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.

Please Use from string instead of int--->

builder.Entity<IdentityUserRole<string>>(b =>
{
    b.HasKey(i => new {i.UserId, i.RoleId});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM