LoginSignup
10
5

More than 1 year has passed since last update.

.Net6 + Npgsql.EntityFrameworkCore.PostgreSQL(Ver6.0)にしたらハマったこと

Posted at

問題

2021年11月8日(日本時間では9日)に.Net6がローンチされたので、早速アプデ
EntityFrameworkCore(EFCore)を使っているので、Npgsql.EntityFrameworkCore.PostgreSQLもVer6.0に上げたら
Date型でエラーが発生でハマった(小一時間)

現象

PostgresのDate型のカラムをEFCoreで取得すると

System.InvalidCastException: Cannot write DateTime with Kind=Local to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array/range. See the Npgsql.EnableLegacyTimestampBehavior AppContext switch to enable legacy behavior.

なるエラーが突如発生

DotnetでのDateTime型とPostgresのDate型がアンマッチとのこと

解決

解決方法は二つありました

LegacyTimestampBehaviorをTrueにする

    public class TestDbContext : DbContext
    {
        public TestDbContext(DbContextOptions<TestDbContext> options)
            : base(options)
        {
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);//<---この行を追加
        }
    }

この方法は.Net6よりも前と同じ動作にするようです。

DateTime型を変える

.Net6(C# 10?)からサポートされたDayOnly型に変更しましょう。
これは日付のみの型でPostgresのDate型とピッタリですね。
日付検索するときも便利です。

Npgsqlの元ネタです

10
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5