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.
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.
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.
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.
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.

Lastly, update the database.
dotnet ef database update

That’s it. It’s very simple to seed a users & roles in EF core!
Related blog post: Data Seeding Made Easier in ASP.NET Core & EF Core
If you have some questions or comments, please drop it below 👇 :)
