Skip to content

Commit

Permalink
Handle Dot Net 9 upgrade PendingModelChangesWarning for AB#16871
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianMaki committed Dec 5, 2024
1 parent 0142fac commit 47951e4
Showing 1 changed file with 48 additions and 3 deletions.
51 changes: 48 additions & 3 deletions Apps/JobScheduler/src/Jobs/DbMigrationsJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@
// -------------------------------------------------------------------------
namespace HealthGateway.JobScheduler.Jobs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Hangfire;
using HealthGateway.Database.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Npgsql;

/// <summary>
/// Runs the database migrations as needed.
Expand Down Expand Up @@ -50,9 +57,47 @@ public DbMigrationsJob(ILogger<DbMigrationsJob> logger, GatewayDbContext dbConte
[DisableConcurrentExecution(ConcurrencyTimeout)]
public async Task MigrateAsync(CancellationToken ct = default)
{
this.logger.LogInformation("Applying database migrations");
await this.dbContext.Database.MigrateAsync(ct);
this.logger.LogInformation("Applied database migrations");
const string jobName = nameof(this.MigrateAsync);

this.logger.LogInformation(
"Job '{JobName}' - Checking for pending database migrations",
jobName);

// Retrieve all migrations that are defined in the application's assembly
IEnumerable<string> pendingMigrations = await this.dbContext.Database.GetPendingMigrationsAsync(ct);

if (pendingMigrations.Any())
{
this.logger.LogInformation(
"Job '{JobName}' - Pending migrations found. Applying database migrations...",
jobName);

// Retrieve the service provider from the current DbContext
IServiceProvider serviceProvider = this.dbContext.GetInfrastructure();
NpgsqlDataSource dataSource = serviceProvider.GetRequiredService<NpgsqlDataSource>();

// Create a new DbContextOptionsBuilder with the required configuration
DbContextOptionsBuilder<GatewayDbContext> optionsBuilder = new();
optionsBuilder
.UseNpgsql(
dataSource,
builder => builder.MigrationsHistoryTable("__EFMigrationsHistory", "gateway"))
.ConfigureWarnings(warnings => warnings.Ignore(RelationalEventId.PendingModelChangesWarning));

// Use a temporary DbContext for applying migrations
await using (GatewayDbContext migrationDbContext = new(optionsBuilder.Options))
{
await migrationDbContext.Database.MigrateAsync(ct);
}

this.logger.LogInformation("Applied database migrations successfully");
}
else
{
this.logger.LogInformation(
"Job '{JobName}' - No pending migrations found. Skipping migration step",
jobName);
}
}
}
}

0 comments on commit 47951e4

Please sign in to comment.