fix(postgres): run Postgres type-mapping block at END of OnModelCreating
This commit is contained in:
@@ -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<Domain.Device>(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})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user