NodaTime.Duration 未被 EF Core 识别为原始类型

NodaTime.Duration not recognized as primitive type by EF Core

我正在使用 EF Core + Npgsql + NodaTime。在数据库配置中,我使用 .UseNodaTime() 选项,到目前为止它工作正常 - 所有 NodaTime.Instant 类型的实体道具都正确映射到 timestamp PG 类型。但是现在我想添加 NodaTime.Duration 类型的道具,根据文档,它应该映射到 PG interval:

    public class TestEntity : EntityBase<long>
    {
        public Duration Duration { get; set; }
        public Instant DateTime { get; set; }
    }

当我尝试为上面的实体生成新的迁移时,出现以下异常:

The property 'TestEntity.Duration' could not be mapped, 
because it is of type 'Duration' which is not a supported primitive type or a valid entity type

所以我想我会自己编写值转换器来将持续时间映射到 TimeSpan,这是映射到 PG 的默认 .net 类型 interval:

    public class TestEntityConfiguration : IEntityTypeConfiguration<TestEntity>
    {
        public void Configure(EntityTypeBuilder<TestEntity> builder)
        {
            builder.Property(e => e.Duration).HasConversion(
                duration => duration.ToTimeSpan(),
                timeSpan => Duration.FromTimeSpan(timeSpan)
            );
        }
    }

自定义值转换器迁移生成成功:

CREATE TABLE test_entities (
    id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY,
    created_at timestamp NOT NULL,
    updated_at timestamp NOT NULL,
    is_deleted boolean NOT NULL,
    duration interval NOT NULL, -- OK
    date_time timestamp NOT NULL,
    CONSTRAINT pk_test_entities PRIMARY KEY (id)
);

但是当我尝试插入具有一定持续时间的新 TestEntity 时:

            db.TestEntities.Add(new TestEntity()
            {
                Duration = Duration.FromMinutes(30),
                DateTime = DateTime.Now.AsUtc().ToInstant()
            });

            db.SaveChanges();

我收到以下错误:

System.InvalidCastException
Can't write CLR type System.TimeSpan with handler type IntervalHandler

我不确定我在这里遗漏了什么 - 我是否需要 Npgsql 的额外配置(除了 .UseNodaTime())?

包版本:

        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.8" />
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.9" />
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.3" />
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite" Version="3.1.3" />
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="3.1.3" />

added in version 5 of the provider 支持将 NodaTime Duration 映射到 PostgreSQL interval,您必须升级才能使用它。请注意,即将发布的版本 6(将在几周内发布)以各种方式显着改进了 NodaTime 支持 - 我建议您等待并切换到该版本。