summaryrefslogtreecommitdiff
path: root/HBContext.cs
blob: 45b8852a539c3a2ba73e5bbdbb89d1f7e928144d (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
49
50
51
52
53
54
55
56
57
58
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,
                Guid     = new("EBDAD4F8-455A-4351-8017-1D4854D6FA38"),
                Source   = TagSource.Internal,
                Name     = "nsfw"
            },
            new() {
                ObjectId = -2,
                Guid     = new("EA212801-5BCC-4C0E-814F-FB9D30DB58BC"),
                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();
    }
}