Skip to content
Snippets Groups Projects

Issue/xxxx enable db migration

Merged L. Ellenbeck requested to merge Issue/xxxx-enableDbMigration into dev
All threads resolved!
Files
69
using Coscine.Api.Core.Repository;
using Microsoft.EntityFrameworkCore;
namespace Coscine.Api.Extensions;
/// <summary>
/// Provides extension methods for database migration on a <see cref="WebApplication"/>.
/// </summary>
public static class MigrationManagerExtensions
{
/// <summary>
/// Migrates the database using Entity Framework Core on the provided <paramref name="webApp"/>.
/// </summary>
/// <param name="webApp">The <see cref="WebApplication"/> instance.</param>
/// <returns>The same <paramref name="webApp"/> instance after attempting the migration.</returns>
public static WebApplication MigrateDatabase(this WebApplication webApp)
{
// Creating a scope using the services of the WebApplication
using (var scope = webApp.Services.CreateScope())
{
// Retrieving the logger service for this class from the service provider
var logger = scope.ServiceProvider.GetRequiredService<ILogger<WebApplication>>();
// Obtaining the RepositoryContext service within the scope
using var appContext = scope.ServiceProvider.GetRequiredService<RepositoryContext>();
try
{
// Only migrate on a relational DB!
if (appContext.Database.IsRelational())
{
appContext.Database.GetPendingMigrations().ToList().ForEach(migration =>
{
// Logging the migration
logger.LogInformation("Applying migration {migration}.", migration);
});
// Attempting database migration using Entity Framework Core
appContext.Database.Migrate();
}
}
catch (Exception ex)
{
// Logging the exception using the obtained logger
logger.LogError(ex, "Database migration failed.");
// Rethrowing the exception to maintain the original behavior
throw;
}
}
// Returning the WebApplication after attempting the migration
return webApp;
}
}
\ No newline at end of file
Loading