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. 问题

参考

环境

软件/系统 版本 说明
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
    

正文

  1. 添加 PostgreSQL 配置文件 postgresql.conf,允许外部连接、指定时区。(这是在本机创建的文件,根据docker-compose.yml配置,会自动加载,对应 - ./data/postgresql.conf:/etc/postgresql/postgresql.conf # 挂载数据库配置文件)
    # 允许所有 IP 连接,否则会导致外部无法连接到 PostgreSQL 数据库
    listen_addresses = '*'
    # 指定时区
    timezone = 'UTC'
    
  2. 将时间转换为带时区的时间格式。
    var date    = DateTime.Now; // DateTime.UtcNow
    var utcDate = DateTime.SpecifyKind(date, DateTimeKind.Utc);
    
  3. 重启数据库、重启应用即可。
posted @ 2025-07-27 17:27  夏秋初  阅读(34)  评论(0)    收藏  举报