How to Seed Users and Roles in Asp.Net Core

In my previous article Creating a new ASP.NET Core Application Project and Setting Up Asp.Net Core Identity we created a new Asp.Net Core project and setup Asp.Net Core identity and database. Now in this article we will create I will show you how to create our initial data in our database.

Advertisements

Using the same project that we build in my previous article Creating a new ASP.NET Core Application Project and Setting Up Asp.Net Core Identity create a new folder inside the Data folder and call it DataInitializer.

Then inside the DataInitializer folder, add a new class and name it UserAndRoleDataInitializer.

UserAndRoleDataInitializer have only one public method which is the SeedData method. It accepts UserManager and RoleManger as parameter and use it to create our user and roles. The code itself is pretty straight forward. We just check if the role already exist if not we will create. The same apply for the user.

using Microsoft.AspNetCore.Identity;
using PayrollApp.Api.Data.Entities;

namespace PayrollApp.Api.Data.DataInitializer
{
    public static class UserAndRoleDataInitializer
    {
        public static void SeedData(UserManager<User> userManager, RoleManager<IdentityRole> roleManager)
        {
            SeedRoles(roleManager);
            SeedUsers(userManager);
        }

        private static void SeedUsers (UserManager<User> userManager)
        {
            if (userManager.FindByEmailAsync("johndoe@localhost").Result == null)
            {
                User user = new User();
                user.UserName = "johndoe@localhost";
                user.Email = "johndoe@localhost";
                user.FirstName = "John";
                user.LastName = "Doe";

                IdentityResult result = userManager.CreateAsync(user, "P@ssw0rd1!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "User").Wait();
                }
            }


            if (userManager.FindByEmailAsync("alex@localhost").Result == null)
            {
                User user = new User();
                user.UserName = "alex@localhost";
                user.Email = "alex@localhost";
                user.FirstName = "Alex";
                user.LastName = "Calingasan";

                IdentityResult result = userManager.CreateAsync(user, "P@ssw0rd1!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Admin").Wait();
                }
            }
        }

        private static void SeedRoles (RoleManager<IdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("User").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "User";
                IdentityResult roleResult = roleManager.
                CreateAsync(role).Result;
            }


            if (!roleManager.RoleExistsAsync("Admin").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "Admin";
                IdentityResult roleResult = roleManager.
                CreateAsync(role).Result;
            }
        }
    }
}
Advertisements

Open your Program.cs and update your Main method like the code below. You might have to resolve some dependency error.

public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();
            using (var scope = host.Services.CreateScope())
            {
                var serviceProvider = scope.ServiceProvider;
                try
                {
                    var userManager = serviceProvider.GetRequiredService<UserManager<User>>();
                    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
                    UserAndRoleDataInitializer.SeedData(userManager, roleManager);
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            host.Run();
        }

Now everytime you run your application it will run UserAndRoleDataInitializer SeedData and try to seed the data.

We will not have a problem for duplicate data since we did our checking before we insert our roles and users.

Advertisements

Related Articles:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s