Skip to content

Commit

Permalink
run migrations on startup
Browse files Browse the repository at this point in the history
  • Loading branch information
Barsonax committed May 26, 2024
1 parent 5c489fa commit 16d5226
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 11 deletions.
3 changes: 2 additions & 1 deletion CleanAspCore.Api.Tests/TestSetup/TestWebApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ protected override IHost CreateHost(IHostBuilder builder)
{ "ConnectionStrings:Default", _pooledDatabase.ConnectionString },
{ "Logging:LogLevel:Microsoft.AspNetCore.Routing", "Information" },
{ "DisableTelemetry", "true" },
{ "DisableOpenApi", "true" }
{ "DisableOpenApi", "true" },
{ "DisableMigrations", "true" }
});
});

Expand Down
20 changes: 20 additions & 0 deletions CleanAspCore/AppConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Reflection;
using CleanAspCore.Data;
using CleanAspCore.Endpoints.Departments;
using CleanAspCore.Endpoints.Employees;
using CleanAspCore.Endpoints.Jobs;
Expand Down Expand Up @@ -80,4 +81,23 @@ internal static void UseOpenApi(this WebApplication app)
app.UseSwagger();
app.UseSwaggerUI();
}

internal static void RunMigrations(this WebApplication app)
{
if (app.Configuration.GetValue<bool?>("DisableMigrations") == true)
return;

if (app.Environment.IsDevelopment())
{
var watchIteration = app.Configuration.GetValue("DOTNET_WATCH_ITERATION", 1);
if (watchIteration == 1)
{
app.EnsureHrContextDatabaseIsCreated();
}
}
else
{
app.MigrateHrContextDatabase();
}
}
}
7 changes: 7 additions & 0 deletions CleanAspCore/Data/HrContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,11 @@ public static void EnsureHrContextDatabaseIsCreated(this IHost host)
var context = serviceScope.ServiceProvider.GetRequiredService<HrContext>();
context.Database.EnsureCreated();
}

public static void MigrateHrContextDatabase(this IHost host)
{
using var serviceScope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
var context = serviceScope.ServiceProvider.GetRequiredService<HrContext>();
context.Database.Migrate();
}
}
11 changes: 1 addition & 10 deletions CleanAspCore/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,10 @@

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
var watchIteration = app.Configuration.GetValue("DOTNET_WATCH_ITERATION", 1);
if (watchIteration == 1)
{
app.EnsureHrContextDatabaseIsCreated();
}
}
app.RunMigrations();

app.UseOpenApi();

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

Expand Down

0 comments on commit 16d5226

Please sign in to comment.