66 lines
2.4 KiB
C#
66 lines
2.4 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
using Moonlight.Api.Infrastructure.Database;
|
|
using MoonlightServers.Api.Infrastructure.Database.Entities;
|
|
|
|
namespace MoonlightServers.Api.Infrastructure.Database;
|
|
|
|
public class DataContext : DbContext
|
|
{
|
|
public DbSet<Node> Nodes { get; set; }
|
|
public DbSet<Template> Templates { get; set; }
|
|
public DbSet<TemplateDockerImage> TemplateDockerImages { get; set; }
|
|
public DbSet<TemplateVariable> TemplateVariablesVariables { get; set; }
|
|
|
|
private readonly IOptions<DatabaseOptions> Options;
|
|
public DataContext(IOptions<DatabaseOptions> options)
|
|
{
|
|
Options = options;
|
|
}
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
{
|
|
if (optionsBuilder.IsConfigured)
|
|
return;
|
|
|
|
optionsBuilder.UseNpgsql(
|
|
$"Host={Options.Value.Host};" +
|
|
$"Port={Options.Value.Port};" +
|
|
$"Username={Options.Value.Username};" +
|
|
$"Password={Options.Value.Password};" +
|
|
$"Database={Options.Value.Database}",
|
|
builder =>
|
|
{
|
|
builder.MigrationsAssembly(typeof(DataContext).Assembly);
|
|
builder.MigrationsHistoryTable("MigrationsHistory", "servers");
|
|
}
|
|
);
|
|
}
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
modelBuilder.HasDefaultSchema("servers");
|
|
|
|
base.OnModelCreating(modelBuilder);
|
|
|
|
modelBuilder.Entity<Template>()
|
|
.ComplexProperty(x => x.FilesConfig, builder => builder.ToJson())
|
|
.ComplexProperty(x => x.LifecycleConfig, builder => builder.ToJson())
|
|
.ComplexProperty(x => x.InstallationConfig, builder => builder.ToJson())
|
|
.ComplexProperty(x => x.MiscellaneousConfig, builder => builder.ToJson());
|
|
|
|
// One-to-many: Template => DockerImages
|
|
modelBuilder.Entity<Template>()
|
|
.HasMany(t => t.DockerImages)
|
|
.WithOne(d => d.Template)
|
|
.HasForeignKey("TemplateId")
|
|
.OnDelete(DeleteBehavior.Cascade);
|
|
|
|
// One-to-one: Template => DefaultDockerImage
|
|
modelBuilder.Entity<Template>()
|
|
.HasOne(t => t.DefaultDockerImage)
|
|
.WithOne()
|
|
.HasForeignKey<Template>("DefaultDockerImageId")
|
|
.OnDelete(DeleteBehavior.SetNull);
|
|
}
|
|
} |