If I understand correctly, you want to seeds roles in the AspNetRoles table. First, register the Role Manager in the Program.cs file. The Role Manager handles all details of adding a role to the AspNetRoles table. Program.cs
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Create a class that takes advantage of the Role Manager to seed the role data.
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace RazorPagesIdentity.Data
{
public class SeedData
{
public static async Task InitializeAsync(IServiceProvider serviceProvider)
{
var _roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if(_roleManager != null)
{
IdentityRole? role = await _roleManager.FindByNameAsync("Admin");
if(role == null)
{
var results = await _roleManager.CreateAsync(new IdentityRole("Admin"));
}
}
}
}
}
Update the Program.cs file to execute the InitializeAsync() method above. Place the code after the builder.build() line.
var app = builder.Build();
//Seed data
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
await SeedData.InitializeAsync(services);
}
This is my DbContext file.
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace RazorPagesIdentity.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
I want to make sure you understand that key are needs to relate the data.