How to call SeedRoles method in Program.cs
The SeedRoles
class should be a static class, you can modify it as below:
//required
//using Microsoft.AspNetCore.Identity;
//using Microsoft.EntityFrameworkCore;
public static class SeedRoles
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new ApplicationDbContext(serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
string[] roles = new string[] { "Owner", "Administrator", "Tests2", "Editor", "Buyer", "Business", "Seller", "Subscriber" };
var newrolelist = new List<IdentityRole>();
foreach (string role in roles)
{
if (!context.Roles.Any(r => r.Name == role))
{
newrolelist.Add(new IdentityRole(role));
}
}
context.Roles.AddRange(newrolelist);
context.SaveChanges();
}
}
}
Note: In my application, the DB context is ApplicationDbContext
, you can chnage it to yours.
Then, in the program.cs file, you can call the seed role method after the var app = builder.Build();
line, code like this:
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //enable Identity Role
.AddEntityFrameworkStores<ApplicationDbContext>() ;
builder.Services.AddControllersWithViews();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
SeedRoles.Initialize(services);
}
The result as below:
More detail information, you can check the official document and sample.