using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Enmarcha.Backend.Data.Models; using System.Text.Json; namespace Enmarcha.Backend.Data; public class AppDbContext : IdentityDbContext { public AppDbContext(DbContextOptions options) : base(options) { } public DbSet ServiceAlerts { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Rename Identity tables to snake_case for PostgreSQL builder.Entity(b => b.ToTable("users")); builder.Entity(b => b.ToTable("roles")); builder.Entity>(b => b.ToTable("user_roles")); builder.Entity>(b => b.ToTable("user_claims")); builder.Entity>(b => b.ToTable("user_logins")); builder.Entity>(b => b.ToTable("role_claims")); builder.Entity>(b => b.ToTable("user_tokens")); // ServiceAlert configuration builder.Entity(b => { b.HasKey(x => x.Id); static ValueComparer JsonComparer() where T : class => new( (x, y) => JsonSerializer.Serialize(x, (JsonSerializerOptions?)null) == JsonSerializer.Serialize(y, (JsonSerializerOptions?)null), c => JsonSerializer.Serialize(c, (JsonSerializerOptions?)null).GetHashCode(), c => JsonSerializer.Deserialize( JsonSerializer.Serialize(c, (JsonSerializerOptions?)null), (JsonSerializerOptions?)null)!); // Store Selectors as JSONB b.Property(x => x.Selectors) .HasColumnType("jsonb") .HasConversion( v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null), v => JsonSerializer.Deserialize>(v, (JsonSerializerOptions?)null) ?? new List(), JsonComparer>()); // Store TranslatedStrings as JSONB b.Property(x => x.Header) .HasColumnType("jsonb") .HasConversion( v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null), v => JsonSerializer.Deserialize(v, (JsonSerializerOptions?)null) ?? new(), JsonComparer()); b.Property(x => x.Description) .HasColumnType("jsonb") .HasConversion( v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null), v => JsonSerializer.Deserialize(v, (JsonSerializerOptions?)null) ?? new(), JsonComparer()); // Store InfoUrls as JSONB array b.Property(x => x.InfoUrls) .HasColumnType("jsonb") .HasConversion( v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null), v => JsonSerializer.Deserialize>(v, (JsonSerializerOptions?)null) ?? new List(), JsonComparer>()); }); } }