You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ABP AuthServer模块对接PostgreSQL遇DateTime异常,添加开关仍未解决

解决ABP AuthServer模块初始化时Npgsql DateTime范围异常的问题

问题根源

该异常是由于PostgreSQL的timestamp类型支持无限值(infinity/-infinity),但.NET的DateTime类型不允许超出MinValue(0001-01-01)到MaxValue(9999-12-31)的范围。你之前设置的开关未生效,大概率是因为设置时机不对,或者配置不完整。

解决方案

  1. 修正开关设置时机与名称
    将开关配置移到模块的静态构造函数中(确保在Npgsql组件加载前生效),同时注意开关名称的正确大小写:

    public class AuthServerModule : AbpModule
    {
        static AuthServerModule()
        {
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
        }
    
        // 原有ConfigureServices等方法...
    }
    
  2. 全局配置EF Core与Npgsql的DateTime映射
    在模块的ConfigureServices中配置DbContext,强制DateTime映射为PostgreSQL的timestamp类型,避免时区转换引入的无限值问题:

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.Configure<AbpDbContextOptions>(options =>
        {
            options.UseNpgsql(builder =>
            {
                builder.UseDateTimeKind(DateTimeKind.Utc);
                builder.MapDateTimeToTimestamp();
                // 可选:开启引号映射策略,避免字段名冲突
                builder.MappingStrategy = NpgsqlMappingStrategy.Quoted;
            });
        });
    
        // 其他服务配置...
    }
    
  3. 检查初始化种子数据
    排查项目中所有初始化的种子数据,确保没有设置超出.NET DateTime范围的值(比如DateTime.MinValue或年份小于1/大于9999的时间),修正这类非法值。

  4. 更新Npgsql相关包版本
    将Npgsql和Npgsql.EntityFrameworkCore.PostgreSQL更新到最新稳定版,旧版本可能存在开关不生效的已知bug。

内容的提问来源于stack exchange,提问作者user23084570

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:07:54