57 lines
2.2 KiB
C#
57 lines
2.2 KiB
C#
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";
|
|
|
|
/// <summary>
|
|
/// Tries to migrate the data file.
|
|
/// </summary>
|
|
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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Add the database to the DI system
|
|
/// </summary>
|
|
public static void AddDatabase(this IServiceCollection serviceCollection, string path2DataFile, bool createWhenNecessary = true)
|
|
{
|
|
serviceCollection.AddDbContext<DataContext>(options => options.UseSqlite($"Filename={path2DataFile};Mode={(createWhenNecessary ? DB_READ_WRITE_CREATE_MODE : DB_READ_WRITE_MODE)}"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets up the DI & db context ready for the EF tooling.
|
|
/// </summary>
|
|
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<DataContext>(options => options.UseSqlite($"Filename={dataFile};Mode=ReadWriteCreate"));
|
|
});
|
|
|
|
return builder;
|
|
}
|
|
}
|