Files
social-media/src/Infrastructure/Data/ApplicationDbContextInitializer.cs
2024-10-20 15:48:46 -04:00

70 lines
1.9 KiB
C#

using Hutopy.Infrastructure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Hutopy.Infrastructure.Data;
public static class InitializerExtensions
{
public static async Task InitialiseApplicationDatabaseAsync(this WebApplication app)
{
using var scope = app.Services.CreateScope();
var initializer = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitializer>();
await initializer.InitialiseAsync();
await initializer.SeedAsync();
}
}
public class ApplicationDbContextInitializer(
ILogger<ApplicationDbContextInitializer> logger,
ApplicationDbContext context,
RoleManager<ApplicationRole> roleManager)
{
public async Task InitialiseAsync()
{
try
{
await context.Database.MigrateAsync();
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while initialising the database.");
throw;
}
}
public async Task SeedAsync()
{
try
{
await TrySeedAsync();
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while seeding the database.");
throw;
}
}
private async Task TrySeedAsync()
{
var administratorRole = new ApplicationRole(KnownRoles.Administrator);
if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
{
await roleManager.CreateAsync(administratorRole);
}
var roleCreator = new ApplicationRole(KnownRoles.Creator);
if (roleManager.Roles.All(r => r.Name != roleCreator.Name))
{
await roleManager.CreateAsync(roleCreator);
}
}
}