0

I am getting the oddest of errors when I attempt to assign roles to user the role is their in the db fine.

But the function used to assign roles is causing an exception

public static async Task<IdentityResult> 
AssignRoles(IServiceProvider services,ApplicationUser user, 
            string email, string[] roles)
{
    IdentityResult result = new IdentityResult();            
    UserManager<ApplicationUser> _userManager = 
    services.GetService<UserManager<ApplicationUser>>();            
    result = await _userManager.AddToRolesAsync(user, roles);
    
    return result;
 }

The exception that I am getting is after the AddToRolesAsync is called

Invalid Operation the connection is closed

Code I use to call above

public async static void CreateParent(IServiceProvider serviceProvider)
{
  var context = new DBContext();// 
      serviceProvider.GetService<DBContext>();

  string[] roles = new string[] { "Parent" };

  foreach (string role in roles)
  {
    var roleStore = new RoleStore<IdentityRole>(context);
    if (!context.Roles.Any(r => r.Name == role))
    {
        await roleStore.CreateAsync(new IdentityRole(role));
    }
}
        
var user = new ApplicationUser
{
    FirstName = "Parent",
    LastName = "Two",
    Email = "parenttwo@apps-mobileapp.com",
    NormalizedEmail ="PARENTTWO@APPS-MOBILEAPP.COM",
    UserName = "parenttwo@apps-MOBILEAPP.com",
    NormalizedUserName = "PARENTTWO@APPS-MOBILEAPP.COM",
    PhoneNumber = "+111111111111",
    EmailConfirmed = true,
    PhoneNumberConfirmed = true,
    SecurityStamp = Guid.NewGuid().ToString("D")
};

var db = new DBContext();
if (!db.Users.Any(u => u.UserName == user.UserName))
{
    var password = new PasswordHasher<ApplicationUser>();
    var hashed = password.HashPassword(user, "Test12345!");
    user.PasswordHash = hashed;
    
    var userStore = new UserStore<ApplicationUser>(context);
    var result = await userStore.CreateAsync(user);
}

await AssignRoles(serviceProvider,user, user.Email, roles);

await db.SaveChangesAsync();

}

But its the AddToRolesAsync it fails with the error mentioned above, I am calling it form the startup class as such?

public void Configure(IApplicationBuilder app, 
                      IWebHostEnvironment env,IServiceProvider 
                      service)
{
   SampleData.CreateParent(service);
}
c-sharp-and-swiftui-devni
  • 3,743
  • 4
  • 39
  • 100

0 Answers0