首页 > 解决方案 > Entity Framework Core NodaTime 按日期分组

问题描述

我正在使用 NodaTime 和 Entity Framework Core,现在我正在尝试按日期对查询进行分组,尽管我使用Instant的是字段数据类型。据我了解,使用 dateColumn.Date (使用 DateTime 时)应该可以工作并将查询转移到date_trunc('day', dateColumn),但是如何使用 NodaTimeInstant类型来实现呢?

我看到的问题是 Instant 需要通过时区才能解决这一天,这会抛出

要么以可以翻译的形式重写查询......

标签: entity-framework-corenpgsqlnodatime

解决方案


If you need to perform operations with human calendar units (e.g. days, months...), then considering using LocalDateTime instead. The idea of Instant is precisely that it doesn't support human calendar operations etc.

Something like this should work:

_ = await ctx.Blogs.GroupBy(b => b.Creation.Date).CountAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseNpgsql(@"...", o => o.UseNodaTime());
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public LocalDateTime Creation { get; set; }
}

推荐阅读