-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbManager.cs
80 lines (62 loc) · 1.97 KB
/
DbManager.cs
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
69
70
71
72
73
74
75
76
77
78
79
80
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Brainstorm.Data;
public class DbManager : IDisposable
{
readonly bool destroy;
public AppDbContext Context { get; private set; }
public string Connection => Context.Database.GetConnectionString();
static string GetConnectionString(string env, bool isUnique)
{
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("connections.json")
.AddEnvironmentVariables()
.Build();
string connection = config.GetConnectionString(env);
if (isUnique)
connection = $"{connection}-{Guid.NewGuid()}";
Console.WriteLine($"Connection string: {connection}");
return connection;
}
static AppDbContext GetDbContext(string connection)
{
var builder = new DbContextOptionsBuilder<AppDbContext>()
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.UseSqlServer(connection);
return new AppDbContext(builder.Options);
}
public DbManager(string env = "App", bool destroy = false, bool isUnique = false)
{
this.destroy = destroy;
Context = GetDbContext(GetConnectionString(env, isUnique));
}
public void Initialize()
{
if (destroy)
Context.Database.EnsureDeleted();
Context.Database.Migrate();
}
public Task<bool> Destroy() => Context.Database.EnsureDeletedAsync();
public async Task<bool> InitializeAsync()
{
try
{
if (destroy)
await Destroy();
await Context.Database.MigrateAsync();
return true;
}
catch
{
return false;
}
}
public void Dispose()
{
Console.WriteLine($"Disposing {Connection}");
if (destroy)
Context.Database.EnsureDeleted();
Context.Dispose();
GC.SuppressFinalize(this);
}
}