問題
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の元ネタです