ASP.NET Core MVC 解决 EF Core 连接 PostgreSQL 失败与数据库存储 DateTime 字段出现 Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported. 问题
参考
- DeepSeek
- 豆包
- https://deepinout.com/postgresql/postgresql-questions/587_postgresql_net_postgres_ef_core_cannot_write_datetime_with_kindlocal_to_postgresql_type_timestamp_with_time_zone.html
- https://zhuanlan.zhihu.com/p/628445292
- https://www.cnblogs.com/VAllen/p/abp-pgsql-timestamp-with-time-zone.html
环境
| 软件/系统 | 版本 | 说明 |
|---|---|---|
| Windows | windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器 | |
| Microsoft Visual Studio | Community 2022 (64 位) - Current 版本 17.14.9 | |
| Visual Studio Code | 1.102.2 | |
| Docker Engine | v28.3.2 | Docker 桌面工具 |
| Docker | 28.3.2 | |
| pgAdmin4 | 9.0 | PostgreSQL 数据库管理软件 |
| PostgreSQL | 15 | |
| .NET | 8 | |
| ASP.NET Core MVC | ASP.NET Core MVC in .NET 8.0 | |
| Microsoft.EntityFrameworkCore.Design | 8.0.18 | nuget 依赖 |
| Microsoft.EntityFrameworkCore.Tools | 8.0.18 | nuget 依赖 |
| Npgsql.EntityFrameworkCore.PostgreSQL | 8.0.11 | nuget 依赖 |
- PostgreSQL 容器参数 docker-compose.yml
name: XiaQiuChuApp services: postgres: image: postgres:15-alpine container_name: postgres environment: POSTGRES_USER: postgres # 自定义用户名 POSTGRES_PASSWORD: postgres # 自定义密码 POSTGRES_DB: mydb # 自定义初始数据库名 volumes: - ./data/postgres:/var/lib/postgresql/data # 挂载数据库数据到本地 - ./data/postgresql.conf:/etc/postgresql/postgresql.conf # 挂载数据库配置文件 ports: - "5432:5432" # 暴露 PostgreSQL 端口 restart: unless-stopped command: postgres -c config_file=/etc/postgresql/postgresql.conf
正文
- 添加 PostgreSQL 配置文件
postgresql.conf,允许外部连接、指定时区。(这是在本机创建的文件,根据docker-compose.yml配置,会自动加载,对应- ./data/postgresql.conf:/etc/postgresql/postgresql.conf # 挂载数据库配置文件)# 允许所有 IP 连接,否则会导致外部无法连接到 PostgreSQL 数据库 listen_addresses = '*' # 指定时区 timezone = 'UTC' - 将时间转换为带时区的时间格式。
var date = DateTime.Now; // DateTime.UtcNow var utcDate = DateTime.SpecifyKind(date, DateTimeKind.Utc); - 重启数据库、重启应用即可。
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/19007582
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/p/19007582
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。

浙公网安备 33010602011771号