MVC5: UserManager.AddToRole(): “Error Adding User to Role: UserId not found”?

前端 未结 6 1794
名媛妹妹
名媛妹妹 2020-12-25 13:33

I have been experimenting with MVC5/EF6 and trying out the new Identity Authentication with Code-First Migrations. Everything in the solution is currently building and I can

6条回答
  •  借酒劲吻你
    2020-12-25 13:55

    I would avoid using the UserManager and RoleManager in your Seed method. Instead I would only use the context. Something I use is the following which creates a user and assigns him to a role:

    protected override void Seed(DbModelContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context", "Context must not be null.");
        }
    
        const string UserName = "User";
        const string RoleName = "UserRole";
    
        var userRole = new IdentityRole { Name = RoleName, Id = Guid.NewGuid().ToString() };
        context.Roles.Add(userRole);
    
        var hasher = new PasswordHasher();
    
        var user = new IdentityUser
                       {
                           UserName = UserName,
                           PasswordHash = hasher.HashPassword(UserName),
                           Email = "test@test.com",
                           EmailConfirmed = true,
                           SecurityStamp = Guid.NewGuid().ToString()
                       };
    
        user.Roles.Add(new IdentityUserRole { RoleId = userRole.Id, UserId = user.Id });
    
        context.Users.Add(user);
    
        base.Seed(context);
    }
    

    The Entity classes are custom implementations (because I wanted to use GUIDs as the IDs), but they derive from the framework classes. With that it should work in the same way if you change them to the appropriate framework classes.

    EDIT

    I removed the custom classes and switched them to the framework classes, because there were some confusion.

提交回复
热议问题