Users & roles seeding in an app is optional but it is one of the important tasks you should consider while building your application authentication. Instead of creating a data via your app form, using data seeding, you can directly populate data upon EF migration. This feature is called “Model seed data” or “Data Seeding” and it’s out since EF Core 2.1.

In this blog, we’re going to use this feature to seed users & roles because we want our ASP.NET Core app to have its default user and role data.

FTF (First Things First)

Make sure you already setup your ASP.NET Core app identity models and your database context (DbContext). In this demo, I’m using ASP.NET Core 3.0 and it’s ready for user and role seeding.

Role Seeding

First, let’s seed roles. Inside the OnModelCreating of your DbContext file, add this code.

builder.Entity<Role>().HasData(new List<Role>
{
    new Role {
        Id = 1, 
        Name = "Admin", 
        NormalizedName = "
        ADMIN"
    },
    new Role {
        Id = 2, 
        Name = "Staff", 
        NormalizedName = "STAFF"
    },
});

NormalizedName must always be upper case.

User & User Role Seeding

After we create roles, then we can seed a user with a role attach to it. Place this code after the code from above.

var hasher = new PasswordHasher<User>();
builder.Entity<User>().HasData(
    new User {
        Id = 1, // primary key
        UserName = "admin",
        NormalizedUserName = "ADMIN",
        PasswordHash = hasher.HashPassword(null, "temporarypass"),
        IsActive = true
    },
    new User {
        Id = 2, // primary key
        UserName = "staff",
        NormalizedUserName = "STAFF",
        PasswordHash = hasher.HashPassword(null, "temporarypass"),
        IsActive = true
    }
);

builder.Entity<UserRole>().HasData(
    new UserRole
    {
        RoleId = 1, // for admin username
        UserId = 1  // for admin role
    },
    new UserRole
    {
        RoleId = 2, // for staff username
        UserId = 2  // for staff role
    }
);

As you can see above, we called the PasswordHasher to generate an hash password of temporarypass. We also called the builder.Entity<UserRole> to assign the specific user to a role.

Do the migration

One you finish the steps above, you can now do the migrations and database update using your command line.

dotnet ef migrations add MigrateUserAndRoleSeed

As you notice in the snapshot migration file, there’s a migrationBuilder.InsertData(...) command based from the user and role that we added.

Mark Deanil Vicente User & Role Seed Data

Lastly, update the database.

dotnet ef database update

Mark Deanil Vicente User & Role Seed Data

That’s it. It’s very simple to seed a users & roles in EF core!

If you have some questions or comments, please drop it below 👇 :)