【问题标题】:实体框架核心异常:没有为实体类型“JsonDocument”找到合适的构造函数
【发布时间】:2022-01-20 14:52:37
【问题描述】:

我在运行单元测试时遇到了这个错误。本地测试应用程序时没有错误。使用 JsonDocument 的简化类是:

[Table("configuration")]
public class Configuration: IDisposable
{
    [Column("value", TypeName = "json")]
    [Required]
    public JsonDocument Value { get; set; }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            this.Schema.Dispose();
            this.Value.Dispose();
        }
    }
}

错误是:

System.InvalidOperationException : No suitable constructor was found for entity type 'JsonDocument'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'utf8Json', 'parsedData', 'extraRentedArrayPoolBytes', 'extraPooledByteBufferWriter', 'isDisposable' in 'JsonDocument(ReadOnlyMemory<byte> utf8Json, MetadataDb parsedData, byte[] extraRentedArrayPoolBytes, PooledByteBufferWriter extraPooledByteBufferWriter, bool isDisposable)'.

我搜索了这个错误并发现了这个 Github 问题:https://github.com/npgsql/npgsql/issues/2902

我试过了,效果很好。 还有其他选择吗?我不喜欢扩展我的 DbContext 类的想法,因为这个问题会干扰大约 500 个单元测试,以及许多直接使用 DbContext 的文件。有没有一个优雅的解决方案? 我在单元测试db上下文类中实现的解决方案和github的解决方案是一样的:

public class UnitTestMyDbContext : MyDbContext
{
    public UnitTestMyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Configuration>().Property(p => p.Value)
            .HasConversion(
                v => v.ToJson(),
                v => v.FromJson<JsonDocument>());
    }
}

我也将此页面用作参考: https://www.npgsql.org/efcore/mapping/json.html#jsondocument-dom-mapping

  • 有没有更好的方法来做到这一点?
  • 是否有另一种方法可以在 postgres 中读取 json 数据类型而不将其映射到字符串或 POCO?
  • 有没有办法让单元测试 InMemoryDatabase 配置不太多,以便他们正确读取 JsonDocument 类型?

【问题讨论】:

  • 这不是 NpgSQL 问题。它的 EF Core 提供程序已经可以处理 JsonDocument。失败的是内存中的提供程序 EF Core 尚不支持 JSON 列。 This is planned for EF Core 7。 NpgSQL 使用自己的内置 JSON 提供程序将 JsonDocument 持久化到 jsonb。
  • 一种选择是修改内存提供程序以支持 JsonDocument。 The InMemoryTypeMappingSource 类通过简单地创建一个带有比较器的映射类来为所有值类型、字符串、字节和几何类型创建映射。也许所需要的只是添加 3-4 行来为 JsonDocument 创建映射

标签: c# postgresql entity-framework unit-testing in-memory-database


【解决方案1】:

来自您问题中的链接

“请注意,既不需要数据注释也不需要流畅的 API,因为 JsonDocument 会自动识别并映射到 jsonb。”

JsonDocument 类没有任何属性,因此如果您想将 JsonDocument 用作普通的 Net 类,您首先需要创建具有所需属性的 Net 类。只有在此之后,您才能添加已创建类的 NotMapped 属性并将所有逻辑放入 getter/setter 中。

恕我直言,值不是类属性的最佳名称,因为它在 Net 框架中非常常用作为属性值,而不是名称。所以它可能会引起一些混乱。最好改一下。

【讨论】:

  • 关于 Value 属性名称,当然,但这仅适用于提供的示例代码。类名也被简化了。关于其余的,谢谢!我也去看看。
猜你喜欢
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多