feat: Add initial database migration with FluentMigrator

This commit is contained in:
2025-07-01 11:25:37 -03:00
parent 656137f2bc
commit 075710287d
3 changed files with 108 additions and 3 deletions

View File

@@ -1,20 +1,54 @@
// Importamos los namespaces necesarios
using FluentMigrator.Runner; // <--- AÑADIR
using Mercados.Database.Migrations; // <--- AÑADIR
using Mercados.Infrastructure;
using Mercados.Infrastructure.Persistence;
using System.Reflection; // <--- AÑADIR
var builder = WebApplication.CreateBuilder(args);
// 1. Registramos nuestra fábrica de conexiones como un Singleton.
// Solo se creará una instancia que leerá la configuration una vez.
// --- V INICIO DE NUESTRO CÓDIGO V ---
// 1. Registramos nuestra fábrica de conexiones.
builder.Services.AddSingleton<IDbConnectionFactory, SqlConnectionFactory>();
// 2. Configurar FluentMigrator
builder.Services
.AddFluentMigratorCore()
.ConfigureRunner(rb => rb
// Usar el conector para SQL Server
.AddSqlServer()
// Obtener la cadena de conexión desde appsettings.json
.WithGlobalConnectionString(builder.Configuration.GetConnectionString("DefaultConnection"))
// Definir el ensamblado (proyecto) que contiene las migraciones
.ScanIn(typeof(CreateInitialTables).Assembly).For.Migrations())
// Habilitar el logging para ver qué hacen las migraciones en la consola
.AddLogging(lb => lb.AddFluentMigratorConsole());
// --- ^ FIN DE NUESTRO CÓDIGO ^ ---
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// --- V INICIO DE NUESTRO CÓDIGO DE EJECUCIÓN V ---
// 3. Ejecutar las migraciones al iniciar la aplicación (ideal para desarrollo y despliegues sencillos)
// Obtenemos el "scope" de los servicios para poder solicitar el MigrationRunner
using (var scope = app.Services.CreateScope())
{
var migrationRunner = scope.ServiceProvider.GetRequiredService<IMigrationRunner>();
// Ejecuta las migraciones pendientes
migrationRunner.MigrateUp();
}
// --- ^ FIN DE NUESTRO CÓDIGO DE EJECUCIÓN ^ ---
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{