Hello,

I am writing this article to show you how to create and assign user role. Create a new asp.net web application project with MVC template along with individual authentication. You have noticed that  AspNetRoles, AspNetUsers etc tables are already  available in our project . So, we can make use of these  tables to fulfill our need . Find and open the Startup.cs file from the solution explorer .You can add  here function to create roles.

In this function we are making our database object with name context  and role manager object . Then we are checking whether visitor role already exist in our roles table if this role exist then we do not create this role  and vice versa. For creating a role we first create role object  then give role name to this and then we create that role . Like this 


After that you need to call this function in configuration method to make it work.


Built your project and run  . Your roles are being added . You can verify it by opening your AspNetRoles  table .

Now this will show how you can assign these roles to user .

You need to add new column in users table with name UserRole .For this go to  Model->Identity.cs open it and add user role property . 


After this you need to  perform migrations because you are updating a users table by adding a new column with the name UserRole . For this  search  and open package manager console in visual studio and pass these three commands.

  1. Enable-migration 
  2. Add-migration
  3. Update-Database

Now, add  a UserRole property in RegisterViewModel. For this go to Model->AccountViewModel open it and  find RegisterViewModel and add UserRole property in it .


Go to Views->Account->Register.cshtml open it and add the following  for display.


After that go to the Controller->AccountController .

Find the Register method and then add the UserRole and make it mapping to other tables like AspNetUserRoles table as well.

Now build the project and run it . You should now understand how to create and assign roles to users.

If you like this article feel free to share it with your friends .