From 65dee642d12731421595c4da072c8d505e3be3b2 Mon Sep 17 00:00:00 2001 From: David Eggenberger Date: Sun, 22 Sep 2024 21:04:30 +0200 Subject: [PATCH] create db if not exists --- .../Features/EFCore/DbUp/Registrator.cs | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/Source/Shared/Features/EFCore/DbUp/Registrator.cs b/Source/Shared/Features/EFCore/DbUp/Registrator.cs index 39c80502..e3e30879 100644 --- a/Source/Shared/Features/EFCore/DbUp/Registrator.cs +++ b/Source/Shared/Features/EFCore/DbUp/Registrator.cs @@ -1,4 +1,5 @@ using DbUp; +using Microsoft.Data.SqlClient; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Shared.Features.EFCore.Configuration; @@ -9,20 +10,36 @@ namespace Shared.Features.EFCore.DbUp { public static class Registrator { - public static IServiceCollection AddDbUpMigration(this IServiceCollection services) + public static async Task AddDbUpMigration(this IServiceCollection services) { using var serviceProvider = services.BuildServiceProvider(); var isProduction = serviceProvider.GetRequiredService().HostingEnvironment.IsProduction(); var efCoreConfiguration = serviceProvider.GetRequiredService(); + var connectionString = isProduction ? efCoreConfiguration.SQLServerConnectionString_Prod : efCoreConfiguration.SQLServerConnectionString_Dev; var upgrader = DeployChanges.To - .SqlDatabase(isProduction ? efCoreConfiguration.SQLServerConnectionString_Prod : efCoreConfiguration.SQLServerConnectionString_Dev) + .SqlDatabase(connectionString) .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly()) - .JournalToSqlTable("dbo", "DbUP_MigrationHistory") + .JournalToSqlTable("dbo", "MigrationHistory_DbUP") .LogToConsole() .Build(); + if (upgrader.TryConnect(out string _) is false) + { + var sqlConnectionParameters = connectionString.Split(';'); + var databaseName = sqlConnectionParameters[1].Split("=")[1]; + var serverConnectionString = string.Join(";", sqlConnectionParameters.Where(e => e.StartsWith("Database") is false)); + + using (var connection = new SqlConnection(string.Join("", serverConnectionString))) + { + connection.Open(); + var command = connection.CreateCommand(); + command.CommandText = $"CREATE DATABASE {databaseName}"; + await command.ExecuteNonQueryAsync(); + } + } + var scripts = upgrader.GetScriptsToExecute(); foreach (var script in scripts) {