How to seed an Admin user in EF Core 2.1.0?

J86 picture J86 · Jun 10, 2018 · Viewed 21.8k times · Source

I have an ASP.NET Core 2.1.0 application using EF Core 2.1.0.

How do I go about seeding the database with Admin user and give him/her an Admin role? I cannot find any documentation on this.

Answer

Zubair Rana picture Zubair Rana · Jul 28, 2018

As user cannot be seeded in a normal way in Identity just like other tables are seeded using .HasData() of .NET Core 2.1.

Microsoft Recommendation: For data that requires calls to external API, such as ASP.NET Core Identity users creation it is recommended to use custom initialization logic.

Seed Roles in .NET Core 2.1 using code given below in ApplicationDbContext Class :

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });
    }

Seed Users With Roles by Following the steps given below.

Step 1: New class creation

public static class ApplicationDbInitializer
{
    public static void SeedUsers(UserManager<IdentityUser> userManager)
    {
        if (userManager.FindByEmailAsync("[email protected]").Result==null)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = "[email protected]",
                Email = "[email protected]"
            };

            IdentityResult result = userManager.CreateAsync(user, "PasswordHere").Result;

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

Step 2: Now Modify ConfigureServices method in Startup.cs class.

Before Modification:

services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

After Modification:

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

Step 3: Modify parameters of Configure Method in Startup.cs class.

Before Modification :

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //..........
    }

After modification :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<IdentityUser> userManager)
    {
        //..........
    }

Step 4 : Calling method of our Seed (ApplicationDbInitializer) class:

ApplicationDbInitializer.SeedUsers(userManager);

Note: You can also Seed Roles just like users by Injecting the RoleManager along with UserManager.