【发布时间】: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