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 an
Actually a User
Entity can be seeded in OnModelCreating
, one thing to consider: the ID
s should be predefined. If type string
is used for TKey
identity entities, then there is no problem at all.
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// any guid
const string ADMIN_ID = "a18be9c0-aa65-4af8-bd17-00bd9344e575";
// any guid, but nothing is against to use the same one
const string ROLE_ID = ADMIN_ID;
builder.Entity().HasData(new IdentityRole
{
Id = ROLE_ID,
Name = "admin",
NormalizedName = "admin"
});
var hasher = new PasswordHasher();
builder.Entity().HasData(new UserEntity
{
Id = ADMIN_ID,
UserName = "admin",
NormalizedUserName = "admin",
Email = "some-admin-email@nonce.fake",
NormalizedEmail = "some-admin-email@nonce.fake",
EmailConfirmed = true,
PasswordHash = hasher.HashPassword(null, "SOME_ADMIN_PLAIN_PASSWORD"),
SecurityStamp = string.Empty
});
builder.Entity>().HasData(new IdentityUserRole
{
RoleId = ROLE_ID,
UserId = ADMIN_ID
});
}