-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYCodeLabDbContextFactory.cs
More file actions
68 lines (57 loc) · 2.27 KB
/
Copy pathYCodeLabDbContextFactory.cs
File metadata and controls
68 lines (57 loc) · 2.27 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.ComponentModel;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Npgsql;
using Microsoft.Extensions.Configuration;
using YCodeLab.DB;
namespace YCodeLab.DBFactory;
public class YCodeLabDbContextFactory : IDesignTimeDbContextFactory<YCodeLabDbContext>, IDbContextFactory<YCodeLabDbContext>
{
private readonly string[] _args = [];
public YCodeLabDbContextFactory() { }
public YCodeLabDbContextFactory(string[] args)
{
_args = args;
}
public YCodeLabDbContext CreateDbContext(params string[] args)
{
string? connStr = args.Length > 0 ? args[0] : null;
var environment = Environment.GetEnvironmentVariable("DB_ENVIRONMENT");
if (string.IsNullOrEmpty(environment))
throw new Exception("Environment variable DB_ENVIRONMENT is not specified.");
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environment}.json")
.Build();
connStr ??= config.GetConnectionString("ycodelab-db");
var connUri = config.GetConnectionString("ycodelab-db-uri");
if (connUri is not null)
{
var oConnUri = new Uri(connUri);
var userInfo = oConnUri.UserInfo.Split(':');
connStr = new NpgsqlConnectionStringBuilder
{
Host = oConnUri.Host,
Port = oConnUri.Port,
Username = userInfo[0],
Password = userInfo[1],
Database = oConnUri.AbsolutePath.TrimStart('/'),
SslMode = SslMode.Require,
MaxPoolSize = 30,
Timeout = 15,
CommandTimeout = 15,
}.ToString();
}
if (connStr is null)
throw new InvalidEnumArgumentException("No database connection information provided.");
Console.WriteLine($"Using a database connected with {connStr}");
var optionsBuilder = new DbContextOptionsBuilder<YCodeLabDbContext>()
.UseNpgsql(connStr);
return new YCodeLabDbContext(optionsBuilder.Options);
}
public YCodeLabDbContext CreateDbContext()
{
return CreateDbContext(_args);
}
}