summaryrefslogtreecommitdiff
path: root/HBContext.cs
blob: 04f2d1a90ee32bc10e8d35fd3c1c9faffebdf1c0 (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
42
43
44
45
46
47
48
using Microsoft.EntityFrameworkCore;
using HyperBooru.Services;

namespace HyperBooru;

public class HBContext : DbContext {
    public DbSet<HBObject>      Objects        { get; set; }
    public DbSet<TagDefinition> TagDefinitions { get; set; }
    public DbSet<Tag>           Tags           { get; set; }
    public DbSet<Media>         Media          { get; set; }
    public DbSet<UploadedFile>  UploadedFiles  { get; set; }

    private IConfigService config;

    public HBContext(DbContextOptions<HBContext> options, IConfigService config) : base(options) =>
        this.config = config;

    protected override void OnConfiguring(DbContextOptionsBuilder options) {
        options.UseLazyLoadingProxies();
        options.UseNpgsql(config.DbConnectionString);

        #if DEBUG
        options.EnableSensitiveDataLogging();
        #endif
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        // Don't use shared tables for inherited types
        modelBuilder.Entity<HBObject>().ToTable("Objects");
        modelBuilder.Entity<TagDefinition>().ToTable("TagDefinitions");
        modelBuilder.Entity<Tag>().ToTable("Tags");
        modelBuilder.Entity<Media>().ToTable("Media");
        modelBuilder.Entity<UploadedFile>().ToTable("UploadedFiles");

        // Seed internal tag definitions
        // These should NEVER change
        modelBuilder.Entity<TagDefinition>().HasData(new TagDefinition[] {
            new() { ObjectId = -1, Source = TagSource.Internal, Name = "nsfw"   },
            new() { ObjectId = -2, Source = TagSource.Internal, Name = "ingest" }
        });

        // Implicit tags need some special attention to make many<->many
        // navigations work for the same object type.
        modelBuilder.Entity<TagDefinition>()
            .HasMany(e => e.ImplicitTags)
            .WithMany();
    }
}