diff --git a/src/GreenHome.Infrastructure/Data/GreenHomeDbContext.cs b/src/GreenHome.Infrastructure/Data/GreenHomeDbContext.cs index e4ffe48..b80dbf1 100644 --- a/src/GreenHome.Infrastructure/Data/GreenHomeDbContext.cs +++ b/src/GreenHome.Infrastructure/Data/GreenHomeDbContext.cs @@ -38,24 +38,6 @@ public sealed class GreenHomeDbContext : DbContext { base.OnModelCreating(modelBuilder); - // Postgres-specific mappings (SQL Server path is untouched): - // 1) DateTime -> "timestamp" (no tz): mirrors naive datetime2, accepts any Kind. - // 2) varchar: Postgres counts BYTES, SQL Server's nvarchar counts CHARACTERS. - // x4 keeps char-count semantics for any UTF-8 charset (Persian = 2 bytes/char). - if (Database.ProviderName == "Npgsql.EntityFrameworkCore.PostgreSQL") - { - foreach (var et in modelBuilder.Model.GetEntityTypes()) - { - foreach (var p in et.GetProperties()) - { - if (p.ClrType == typeof(DateTime) || p.ClrType == typeof(DateTime?)) - p.SetColumnType("timestamp"); - else if (p.ClrType == typeof(string) && p.GetMaxLength() is int len) - p.SetColumnType($"character varying({len * 4})"); - } - } - } - modelBuilder.Entity(b => { b.ToTable("Devices"); @@ -515,5 +497,25 @@ public sealed class GreenHomeDbContext : DbContext b.HasIndex(x => x.At); b.HasIndex(x => x.AdminUserId); }); + + // Postgres-specific mappings (SQL Server path is untouched). + // MUST run last: fluent HasMaxLength/HasColumnType calls above set the + // values we adjust here, so this block has to see the final model state. + // 1) DateTime -> "timestamp" (no tz): mirrors naive datetime2, accepts any Kind. + // 2) varchar: Postgres counts BYTES, SQL Server's nvarchar counts CHARACTERS. + // x4 keeps char-count semantics for any UTF-8 charset (Persian = 2 bytes/char). + if (Database.ProviderName == "Npgsql.EntityFrameworkCore.PostgreSQL") + { + foreach (var et in modelBuilder.Model.GetEntityTypes()) + { + foreach (var p in et.GetProperties()) + { + if (p.ClrType == typeof(DateTime) || p.ClrType == typeof(DateTime?)) + p.SetColumnType("timestamp"); + else if (p.ClrType == typeof(string) && p.GetMaxLength() is int len) + p.SetColumnType($"character varying({len * 4})"); + } + } + } } }