| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <[email protected]> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | using System.Reflection; |
| | | 6 | | |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | using Microsoft.EntityFrameworkCore.Infrastructure; |
| | | 9 | | |
| | | 10 | | using Npgsql; |
| | | 11 | | |
| | | 12 | | namespace Api.Database; |
| | | 13 | | |
| | | 14 | | public partial class PGContext(DbContextOptions options, IConfiguration? config = null) : DbContext(options) |
| | | 15 | | { |
| | | 16 | | public string SchemaName { get; set; } = config?["ConnectionStrings:PGSchema"] ?? "public"; |
| | | 17 | | |
| | | 18 | | protected override void OnModelCreating(ModelBuilder modelBuilder) |
| | | 19 | | { |
| | | 20 | | modelBuilder.HasDefaultSchema(SchemaName); |
| | | 21 | | |
| | | 22 | | base.OnModelCreating(modelBuilder); |
| | | 23 | | modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetAssembly(this.GetType()!)!); |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| | | 27 | | => optionsBuilder |
| | | 28 | | .ReplaceService<IModelCacheKeyFactory, SchemaModelCacheKeyFactory>() |
| | | 29 | | .UseSnakeCaseNamingConvention() |
| | | 30 | | .UseValidationCheckConstraints() |
| | | 31 | | .UseNpgsql( |
| | | 32 | | config?.GetConnectionString("PG") ?? "" |
| | | 33 | | , nopts => nopts |
| | | 34 | | .SetPostgresVersion(18, 0) |
| | | 35 | | .UseNodaTime()); |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | public class SchemaModelCacheKeyFactory : IModelCacheKeyFactory |
| | | 39 | | { |
| | | 40 | | public object Create(DbContext context, bool designTime) |
| | 1 | 41 | | { |
| | 1 | 42 | | return context is PGContext pgContext |
| | 1 | 43 | | ? (context.GetType(), pgContext.SchemaName, designTime) |
| | 1 | 44 | | : (context.GetType(), designTime); |
| | 1 | 45 | | } |
| | | 46 | | } |