How to Seed Users and Roles in ASP.NET Core

Now in this article we will create I will show you how to create our initial data in our database.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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("[email protected]").Result == null)
            {
                User user = new User();
                user.UserName = "[email protected]";
                user.Email = "[email protected]";
                user.FirstName = "John";
                user.LastName = "Doe";
                IdentityResult result = userManager.CreateAsync(user, "[email protected]!").Result;
                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "User").Wait();
                }
            }
            if (userManager.FindByEmailAsync("[email protected]").Result == null)
            {
                User user = new User();
                user.UserName = "[email protected]";
                user.Email = "[email protected]";
                user.FirstName = "Alex";
                user.LastName = "Calingasan";
                IdentityResult result = userManager.CreateAsync(user, "[email protected]!").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;
            }
        }
    }
}
Open your Program.cs and update your Main method like the code below. You might have to resolve some dependency error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.

Anjali Punjab

Anjali Punjab is a freelance writer, blogger, and ghostwriter who develops high-quality content for businesses. She is also a HubSpot Inbound Marketing Certified and Google Analytics Qualified Professional.