Search code examples
c#postgresqlentity-framework-core.net-6.0

Upgraded my project to .net 6 now I have time zone in EF Core with postgreSQL


I juste upgraded my web api to .net6 using EFCore and NPGSQL (Postgres). I had to Set a Switch for my code to work: AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

Now EFCore Creates my DateTime fields to 'timestamp with time zone' which breaks everything.

How can I get the old 'timestamp without time zone' for DateTime Types?

Should I remove the LegacyTimestamp switch?

Thanks for your help!


Solution

  • I Fixed it by forcing column type for all DateTime and DateTime? to "timestamp without time zone" by adding the following code in the OnModelCreating of my DBContext.

    foreach (var property in builder.Model.GetEntityTypes()
                     .SelectMany(t => t.GetProperties())
                     .Where
                     ( p
                       => p.ClrType == typeof(DateTime) 
                          || p.ClrType == typeof(DateTime?)
                     )
            )
    {
      property.SetColumnType("timestamp without time zone");
    }
    

    Feels like a hack but it works.