Files
Denso/srcs/RobotNet10/FleetManager/RobotNet10.FleetManager/Data/ApplicationDbExtensions.cs
2026-07-03 16:31:37 +07:00

106 lines
3.7 KiB
C#

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace RobotNet10.FleetManager.Data;
public static class ApplicationDbExtensions
{
extension(IServiceProvider serviceProvider)
{
public async Task SeedApplicationDbAsync()
{
using var scope = serviceProvider.CreateScope();
using var appDb = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await appDb.Database.MigrateAsync();
await appDb.Database.EnsureCreatedAsync();
await appDb.SaveChangesAsync();
await scope.ServiceProvider.SeedRolesAsync();
await scope.ServiceProvider.SeedUsersAsync();
}
private async Task SeedRolesAsync()
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync("Administrator"))
{
await roleManager.CreateAsync(new IdentityRole()
{
Name = "Administrator",
NormalizedName = "ADMINISTRATOR",
});
}
if (!await roleManager.RoleExistsAsync("Distributor"))
{
await roleManager.CreateAsync(new IdentityRole()
{
Name = "Distributor",
NormalizedName = "DISTRIBUTOR",
});
}
if (!await roleManager.RoleExistsAsync("Operator"))
{
await roleManager.CreateAsync(new IdentityRole()
{
Name = "Operator",
NormalizedName = "OPERATOR",
});
}
}
private async Task SeedUsersAsync()
{
using var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (await userManager.FindByNameAsync("admin") is null)
{
var admin = new ApplicationUser()
{
UserName = "admin",
Email = "administrator@phenikaa-x.com",
NormalizedUserName = "ADMINISTRATOR",
NormalizedEmail = "ADMINISTRATOR@PHENIKAA-X.COM",
EmailConfirmed = true,
};
await userManager.CreateAsync(admin, "robotics");
await userManager.AddToRoleAsync(admin, "Administrator");
}
if (await userManager.FindByNameAsync("distributor") is null)
{
var admin = new ApplicationUser()
{
UserName = "distributor",
Email = "distributor@phenikaa-x.com",
NormalizedUserName = "DISTRIBUTOR",
NormalizedEmail = "DISTRIBUTOR@PHENIKAA-X.COM",
EmailConfirmed = true,
};
await userManager.CreateAsync(admin, "distributor");
await userManager.AddToRoleAsync(admin, "Distributor");
}
if (await userManager.FindByNameAsync("Operator") is null)
{
var admin = new ApplicationUser()
{
UserName = "Operator",
Email = "Operator@phenikaa-x.com",
NormalizedUserName = "OPERATOR",
NormalizedEmail = "OPERATOR@PHENIKAA-X.COM",
EmailConfirmed = true,
};
await userManager.CreateAsync(admin, "Operator");
await userManager.AddToRoleAsync(admin, "Operator");
}
}
}
}