0
votes

In VS2013 They taken the Website Administration Tool that you used to be able to set up Roles and membership. I'm trying to add an "Admin" role to my site and add my user name to it but everything I've tried has not worked.

var roleManager = new RoleManager(new RoleStore(context)); roleManager.Create(new IdentityRole("Administrator"));

var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var user = new ApplicationUser { UserName = "admin" };
userManager.Create(user, "admin321");
userManager.AddToRole(user.Id, "Administrator");

Running this in my MVC5 web app. gives me the following error;

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code

Additional information: The entity type IdentityRole is not part of the model for the current context.

the error is produced on the; roleManager.Create(new IdentityRole("Administrator"));

1
Sounds like you need to override the Identity setup to use your custom IdentityRole class. Anyways, they took away the Website Administration Tool, but Thinktecture.IdentityManager fulfills that role, and I believe is a project sponsored by the .NET Foundation. Might be worth looking into it. Here's a blog post about it by a Microsoft employee. - mason
Nice utility but doesn't work with roles yet only users. - Mike Hankey
It does work with roles. Keep in mind, that blog post was written nearly a year ago. Obviously the software hasn't stood still for a year! - mason
It won't built for me during build nuGet is trying to update the solution and returns; 1>G:\Downloads\IdentityManager-master\source\.nuget\NuGet.targets(100,9): error MSB3073: The command ""G:\Downloads\IdentityManager-master\source\.nuget\NuGet.exe" install "G:\Downloads\IdentityManager-master\source\Host\packages.config" -source "" -NonInteractive -RequireConsent -solutionDir "G:\Downloads\IdentityManager-master\source\ "" exited with code 1. - Mike Hankey
You're trying to run IdentityManager from source? While you can do that I'm sure, I'd rather just use NuGet to add it to my app. They have a package for you. - mason

1 Answers

0
votes

Found my own answer here; ASP.Net MVC 4.5 Owin Simple Role Management by Anders G. Nordby

And here is the key code to create an Admin account and assign a user;

using (var context = new ApplicationDbContext())
    {
        var roleStore = new RoleStore<IdentityRole>(context);
        var roleManager = new RoleManager<IdentityRole>(roleStore);

        roleManager.Create(new IdentityRole("Admin"));

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);

        var user = userManager.FindByEmail("[email protected]");
        userManager.AddToRole(user.Id, "Admin");
        context.SaveChanges();
    }