locked
How to create a role in the data base C# web form 4.6.1 RRS feed

  • Question

  • User-2015242085 posted

    Hi

    How to create a role, let's say "Admin" in the data base using RoleManager 

    Friday, May 24, 2019 4:22 PM

Answers

  • User765422875 posted

    Something like this:

    RoleManager = new RoleManager<IdentityRole>(
                      new RoleStore<IdentityRole>(new MyDbContext()));
    
    var roleresult = RoleManager.Create(new IdentityRole("SomeRole"));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 24, 2019 4:34 PM

All replies

  • User765422875 posted

    Something like this:

    RoleManager = new RoleManager<IdentityRole>(
                      new RoleStore<IdentityRole>(new MyDbContext()));
    
    var roleresult = RoleManager.Create(new IdentityRole("SomeRole"));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 24, 2019 4:34 PM
  • User-2015242085 posted

    Hi

    Yes I have a similar code so far, but I don't have "MyDbContext"

    I just have this very simple code https://www.youtube.com/watch?v=D829sZcfpMo for login using Identity C#

    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    if (!roleManager.RoleExists("Admin"))
    {
          var myrole = new IdentityRole();
          myrole.Name = "Admin";
          roleManager.Create(myrole);
    }

    I am missing ApplicationDbContext()

    Friday, May 24, 2019 4:49 PM
  • User765422875 posted

    The ApplicationDbContext() is theDbContext (database).

    You need it to create a role in the database.

    I would walk through this tutorial if you have more questions.

    https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project

    Friday, May 24, 2019 5:11 PM
  • User-2015242085 posted

    Thx for the answer

    I just replace MyDbContext with the default dbcontex:

    IdentityDbContext
    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new IdentityDbContext()));
    if (!roleManager.RoleExists("Admin"))
    {
         var myrole = new IdentityRole();
         myrole.Name = "Admin";
         roleManager.Create(myrole);
    }

    That works! THX

    Friday, May 24, 2019 6:55 PM