//----------------------------------------------------------------------- // // Copyright (c) lanedirt. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // //----------------------------------------------------------------------- namespace AliasServerDb; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.Extensions.Configuration; /// /// PostgreSQL implementation of the AliasServerDbContext. /// public class AliasServerDbContextPostgresql : AliasServerDbContext { /// /// Initializes a new instance of the class. /// public AliasServerDbContextPostgresql() { } /// /// Initializes a new instance of the class. /// /// DbContextOptions. public AliasServerDbContextPostgresql(DbContextOptions options) : base(options) { } /// /// Sets up the connection string if it is not already configured. /// /// DbContextOptionsBuilder instance. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); if (optionsBuilder.IsConfigured) { return; } var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); // Add SQLite connection with enhanced settings var connectionString = configuration.GetConnectionString("AliasServerDbContext"); optionsBuilder .UseNpgsql(connectionString, options => options.CommandTimeout(60)) .UseLazyLoadingProxies(); } /// protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Configure all DateTime properties to use timestamp with time zone in UTC foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { if (property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?)) { property.SetColumnType("timestamp with time zone"); // Add value converter for DateTime properties var converter = new ValueConverter( v => v.ToUniversalTime(), v => v.ToUniversalTime()); property.SetValueConverter(converter); } } } } }