aboutsummaryrefslogtreecommitdiff
path: root/src/Enmarcha.Experimental.ServiceViewer/AppDbContextDesignTimeFactory.cs
blob: 4dcd3202bf17ef027ee9aa8a55d0df38f19c3e85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using Enmarcha.Experimental.ServiceViewer.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace Enmarcha.Experimental.ServiceViewer;

public class AppDbContextDesignTimeFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
                optional: true)
            .AddUserSecrets(typeof(AppDbContext).Assembly, optional: true)
            .AddEnvironmentVariables()
            .Build();

        var builder = new DbContextOptionsBuilder<AppDbContext>();
        var connectionString = configuration.GetConnectionString("Database");
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new InvalidOperationException("Connection string 'Database' not found.");
        }

        var loggerFactory = LoggerFactory.Create(lb =>
        {
            lb
                .AddConsole()
                .SetMinimumLevel(LogLevel.Information);
        });
        builder.UseLoggerFactory(loggerFactory);

        builder.UseNpgsql(
            connectionString,
            options => options.UseNetTopologySuite()
        );

        return new AppDbContext(builder.Options);
    }
}