diff --git a/I18N Commander/DataModel/Setup.cs b/I18N Commander/DataModel/Setup.cs new file mode 100644 index 0000000..44e32d8 --- /dev/null +++ b/I18N Commander/DataModel/Setup.cs @@ -0,0 +1,56 @@ +using DataModel.Database.Common; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace DataModel; + +public static class Setup +{ + private const string ENV_EF_TOOLING_DATABASE = "ENV_EF_TOOLING_DATABASE"; + private const string DB_READ_WRITE_MODE = "ReadWrite"; + private const string DB_READ_WRITE_CREATE_MODE = "ReadWriteCreate"; + + /// + /// Tries to migrate the data file. + /// + public static async Task PerformDataMigration(DataContext dbContext) + { + var pendingMigrations = (await dbContext.Database.GetPendingMigrationsAsync()).ToList(); + foreach (var pendingMigration in pendingMigrations) + { + Console.WriteLine($"The migration '{pendingMigration}' is pending."); + } + + await dbContext.Database.MigrateAsync(); + } + + /// + /// Add the database to the DI system + /// + public static void AddDatabase(this IServiceCollection serviceCollection, string path2DataFile, bool createWhenNecessary = true) + { + serviceCollection.AddDbContext(options => options.UseSqlite($"Filename={path2DataFile};Mode={(createWhenNecessary ? DB_READ_WRITE_CREATE_MODE : DB_READ_WRITE_MODE)}")); + } + + /// + /// Sets up the DI & db context ready for the EF tooling. + /// + public static IHostBuilder Setup4EFTooling(string[] args) + { + var dataFile = Environment.GetEnvironmentVariable(ENV_EF_TOOLING_DATABASE); + if (string.IsNullOrWhiteSpace(dataFile)) + { + Console.WriteLine("In order to use EF tooling, point the environment variable ENV_EF_TOOLING_DATABASE to the data file, which should be used for the EF tooling."); + Environment.Exit(100); + } + + var builder = Host.CreateDefaultBuilder(args); + builder.ConfigureServices((hostContext, serviceCollection) => + { + serviceCollection.AddDbContext(options => options.UseSqlite($"Filename={dataFile};Mode=ReadWriteCreate")); + }); + + return builder; + } +}