たとえば、画面側で「yyyy-mm-dd 0:00:00」というような日時未知数な形式でサーバ側に送信した時、格納先のPostgreSQLのカラムのデータ型がtimestamp with time zone
であったときどのようにして格納すべきかを記載しておきます。
さきほどの「yyyy-mm-dd 0:00:00」の形式で送った場合に下記のエラーが発生します。
Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported.
これは、PostgreSQL のtimestamp with time zone
カラム(timestamptz)に保存するには、UTC形式の DateTime(Kind=Utc)
でなければならないと Npgsql が要求しています。
解決方法(DateTime.SpecifyKind
関数で変換)
DateTime.SpecifyKind
関数を使えば、UTC
表記に変換されテーブルへ格納することができます。
sample.cs
//例
if (book.Published.HasValue)
{
book.Published = DateTime.SpecifyKind(book.Published.Value, DateTimeKind.Utc);
}