James
James

Reputation: 1392

Using UserManager and RoleManager in Microsoft.AspNet.Identity;

I've used this before, and I can't for the life in me figure what's going wrong.

@using System.Data.Entity;
@using Microsoft.AspNet.Identity;
@using Microsoft.AspNet.Identity.EntityFramework;


using(ApplicationDbContext db = new ApplicationDbContext())
{
   var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
   var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

   var user = User.Identity.GetUserId();

        if(user != null)
        {
            string role = "Admin";
            if (!rm.RoleExists(role))
            {
                var roleResult = rm.Create(new IdentityRole(role));
                if (!roleResult.Succeeded) { //error stuff
                };
            }
            if (!um.IsInRole(user, role))
            {
                um.AddToRole(user, role);
            }
        }
}

When I run this I skip past the creating a role element (because I've already added this to the database), but when it gets to the 'is the user in role of Admin' bit, the line um.AddToRole(user, role) is run, but then I receive an error, stating that I have a violation because I am trying to duplicate the key.

I don't understand why the program when debugged says "there is no user with this name which has a role of Admin", and a fraction later when it tries to add that role, I'm presented with "Hey, that user already has a role of Admin and you can't add it again"

Before when I used RoleProviders I had to change my web.config and add info into there, but I haven't done this, because I don't have to!?

It's probably very simple but I'm stuck.

Just for clarity how do I check if the currently logged in user belongs to the role "Admin" with AspNet.Identity.

Kind regards

Upvotes: 7

Views: 9458

Answers (1)

James
James

Reputation: 1392

Ok so the problem turns out that turning lazing loading off causing this problem. I updated the Microsoft Identity to 2.0 but still no joy. Apparently it's a known bug which they are addressing.

Not ideal as I always turn lazy loading off. It's not a massive application, so performance isn't an issue. Just so all are aware.

Upvotes: 2

Related Questions