0

I'm running MVC 5 with Entity Framework 6 and using the ASP.NET Identity authentication. For some reason that I cannot figure out, I cannot seem to assign users to roles and have it stick. Consider the following code:

List<string> roles_1, roles_2;
using (ApplicationDbContext context = new ApplicationDbContext())
{
    UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    userManager.AddToRole(User.Identity.GetUserId(), "Webmaster");
    context.SaveChanges();
    roles_1 = userManager.GetRoles(User.Identity.GetUserId()).ToList();
}
using (ApplicationDbContext context = new ApplicationDbContext())
{
    UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    roles_2 = userManager.GetRoles(User.Identity.GetUserId()).ToList();
}

After running this code, "roles_1" has one item in it ("Webmaster") and "roles_2" is empty. Somehow, the role assignment didn't save between the contexts. When I look directly at the AspNetUserRoles table, there is a row with the link between that user and the role. So, it saved it properly, but the new context isn't loading it properly. Any thoughts as to why this might be?

2
  • Is there a reason why you go directly against the context instead of using the UserManager class? Jun 25, 2014 at 11:45
  • I was using class "AppUserManager" which just extends UserManager but with a custom UserValidator. I've edited the code to make more sense. As you can see, it does create a UserManager class and uses that to add the role.
    – Jordan
    Jun 25, 2014 at 15:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.