I have an Azure Postgres flexible server sitting in a VNet divided into multiple subnets. In a distinct subnet lies an azure app service I am trying to run by publishing it via gitlab. However shortly after launch, this app crashes due to the missing database schema. Basically I can connect to the database via the Azure web app (the CanConnect() check does not throw an exception), but any EF Core operation fails with an error:
the table XX.YY does not exist
Here is the faulty code:
XXDbContext dbContext = scope.ServiceProvider.GetRequiredService<XXDbContext>();
// passes
var canConnect = await dbContext.Database.CanConnectAsync();
if (!canConnect)
{
throw new ApplicationException("Cannot establish connection to the database");
}
var pendingMigrations = (await dbContext.Database.GetPendingMigrationsAsync()).ToList();
logger.LogInformation($"Applying pending migrations in environment...");
foreach (var mug in pendingMigrations)
{
logger.LogInformation(mug);
}
// fails to do anything
if (await TableExistsAsync(dbContext, "Users", "BL") == false)
{
logger.LogWarning("Database tables do not exist. Creating..");
dbContext.Database.EnsureCreated();
logger.LogWarning("Database schema created successfully");
}
if (pendingMigrations.Any())
{
var migrationsList = string.Join(", ", pendingMigrations);
logger.LogWarning($"Database has pending migrations: {migrationsList}");
await dbContext.Database.MigrateAsync();
logger.LogInformation("Migrations applied successfully");
}
// crashes
var userCount = await dbContext.Users.CountAsync();
I have tried another approaches with
var script = dbContext.Database.GenerateCreateScript();
dbContext.Database.ExecuteSqlRaw(script);
It also fails, this time with an SQL formatting error:
FATAL: Database validation failed. The application cannot start.System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.at System.Text.ValueStringBuilder.AppendFormatHelper
For sake of completeness, here is an anonymized version of the connection string I use:
Server=XXX.postgres.database.azure.com;Database=postgres;Port=5432;User Id=admin;Password=YYY;Ssl Mode=Require;
I can't execute any query directly in the Azure Portal as no query editor is available there, and I would greatly prefer to have some automatic behaviour here.
Is my only option to create a VM with bastion just to be able to execute migration SQL scripts?
Thank you for reading my question!