EFCore 中的 Npgsql 无法转换 DateTimeOffset.Date

pup*_*er9 4 c# postgresql npgsql entity-framework-core

这是预期的行为吗?如果是这样,有什么解决方法吗?我正在使用 Net Core 5.0 和 npgsql 5.0

    public async Task<List<long>> GetGuiaIdsWithFilters(DateTime createddate)
    {
        IQueryable<Guia> guiaToReturn = _context.Guia;
        createddate = createddate.ToUniversalTime();
        return await guiaToReturn.Where(g => g.StatusHistory.Any(s.Fecha.Date == createddate.Date)).Select(x => x.Id).ToListAsync();
    }
Run Code Online (Sandbox Code Playgroud)

运行此查询将返回以下错误,我将其隔离为提供程序无法提取日期部分:s.Fecha.Date (DateTimeOffset.Date)。我阅读了文档,DateTimeOffset将在PostgreSQL中存储为timestamptz,但我没有发现常见功能(例如获取日期部分)有任何限制。

无法翻译 LINQ 表达式 [...]。以可翻译的形式重写查询

我可以执行以下解决方法,该方法工作正常,但它似乎是一个效率低得多的查询:

    public async Task<List<long>> GetGuiaIdsWithFilters(DateTime createddate)
    {
        IQueryable<Guia> guiaToReturn = _context.Guia;
        var FromDate = createddate.ToUniversalTime().AddDays(-1);
        var ToDate = createddate.ToUniversalTime.AddDays(1);
        return await guiaToReturn.Where(g => g.StatusHistory.Any(s => s.Fecha > FromDate && s.Fecha < ToDate)).Select(x => x.Id).ToListAsync();
    }
Run Code Online (Sandbox Code Playgroud)

Sha*_*sky 5

Npgsql EF Core 提供程序当前不转换 DateTimeOffset 上的成员(请参阅https://github.com/npgsql/efcore.pg/issues/473)。

请注意,不鼓励将 DateTimeOffset 与 Npgsql 一起使用,因为 PostgreSQL 没有与其对应的类型。DateTimeOffset 映射到 PostgreSQL timestamp with time zone,它实际上没有时区。如果您的时间戳也是 UTC,请考虑使用 DateTime 和 Kind=Utc。

  • 对于任何看到这一点的人来说,Npgsql EF Core 提供程序的 6.0 版添加了对 DateTimeOffset 上的大量翻译的支持 - 但还要注意时间戳处理方面的一些重大重大更改。另请注意,PostgreSQL *没有* 有 DateTimeOffset 类型(不会存储偏移量),因此仅支持 UTC DateTimeOffsets。 (4认同)