PJ.SQL
PJ.SQL

Reputation: 363

Issue creating admin user

I'm having issues creating an admin user using in my controller. What is the problem here?

Here is my code:

public class ProductsController : Controller
{
    private SwagExchangeDb db = new SwagExchangeDb();

    protected override void Initialize(RequestContext requestContext)
    {
        var ac  = new ApplicationDbContext();
        var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(ac));
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ac));
        var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]"};
        userManager.Create(user, "Hello1234!");
        roleManager.Create(new IdentityRole("admin"));
        userManager.AddToRole(user.Id, "admin");

    }

Getting error:

System.InvalidOperationException: 'UserId not found.'

Upvotes: 0

Views: 62

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

You are trying to find the user by the Id which you don't have. You need to query for the user after creating it. Also, you should be disposing the context after finish using it:

protected override void Initialize(RequestContext requestContext)
{
    using (var ac  = new ApplicationDbContext())
    {
        var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(ac));
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ac));
        var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]"};
        userManager.Create(user, "Hello1234!");
        roleManager.Create(new IdentityRole("admin"));

        user = userManager.FindByNameAsync(user.UserName).Result;

        userManager.AddToRole(user.Id, "admin");
    }
}

Upvotes: 1

Related Questions