Skip to content

AddMinutes with Date cannot be translated when upgrading from 5.0.10 #3018

@petergummer

Description

@petergummer

The following program works with Npgsql.EntityFrameworkCore.PostgreSQL 5.0.10, but with 6.0.22 and 8.0 it cannot be translated.

using Microsoft.EntityFrameworkCore;

using System;
using System.Linq;

var ctx = new Ctx();
var utc = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
var query = ctx.Items.Where(i => i.Dt < utc.AddMinutes(i.OffsetMinutes).Date);
Console.WriteLine(query.ToQueryString());

public record Item(int Id, DateTime Dt, int OffsetMinutes);

public class Ctx : DbContext
{
    public DbSet<Item> Items { get; set; } = null!;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("Host=localhost");
}

This is its output with 5.0.10:

-- @__utc_0='2023-12-13T00:58:49.3731327' (DbType = DateTime)
SELECT i."Id", i."Dt", i."OffsetMinutes"
FROM "Items" AS i
WHERE i."Dt" < date_trunc('day', @__utc_0 + CAST((CAST(CAST(i."OffsetMinutes" AS double precision) AS text) || ' mins') AS interval))

And this is the error with 6.0.22 and 8.0:

Unhandled exception. System.InvalidOperationException: The LINQ expression 'DbSet<Item>()
    .Where(i => i.Dt < __utc_0.AddMinutes((double)i.OffsetMinutes).Date)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Note that the expression can be translated if I remove either the AddMinutes or Date, but of course I can't do that because either of those changes would return incorrect results.
I think that this is a duplicate of PomeloFoundation/Pomelo.EntityFrameworkCore.MySql#1715, which was reported last year but is still open.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions