gpt4 book ai didi

c# - Entity Framework Core - 复杂类型映射为 postgres 中的 jsonb 列,但 InMemory 提供程序的映射失败

转载 作者:行者123 更新时间:2023-12-05 04:55:21 25 4
gpt4 key购买 nike

有一个具有如下复杂属性的类型:

[Table("contact")]
public class Contact
{
[Key]
[Column("id")]
public int Id { get; set; }

[Column("details", TypeName = "jsonb")]
public Details Details { get; set; }

...
}
[ComplexType]
public class Details
{
[JsonProperty("firstName")]
public string FirstName { get; set; }

[JsonProperty("middleName")]
public string MiddleName { get; set; }

[JsonProperty("lastName")]
public string LastName { get; set; }
}

对于 pgsql 提供者来说工作正常:

services.AddDbContextPool<ProfileDbContext>((sp, options) =>
{
options.UseNpgsql(connStr,
x =>
{
x.EnableRetryOnFailure();
x.CommandTimeout(120);
});
});

但是在 TestsStartup 中用 InMemory 提供程序替换它时

services.AddDbContextPool<ProfileDbContext>(options =>
{
ServiceProvider sp = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();

options.UseInMemoryDatabase("Profile", _databaseRoot);
options.UseInternalServiceProvider(sp);
});

出现错误:

The entity type 'Details' requires a primary key to be defined.If youintended to use a keyless entity type call 'HasNoKey()'.

如果我通过流畅的配置指定关联 OwnsOne 它适用于 InMemory 但在使用 pgsql 提供程序启动正常启动时失败

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>(c => c.OwnsOne(e => e.Details));
}

我想是由于这个 jsonb 文件类型,InMemory 提供程序不支持它,是吗?

如何处理集成测试?

我们在所有测试中都使用了内存提供程序,但是这个 jsonb 功能似乎破坏了内存提供程序的 lifehack。

最佳答案

InMemory 是一个非常有限的测试解决方案,因为它实际上不能做真实数据库可以做的很多事情——事务、原始 SQL,在本例中是 jsonb 类型。

对于完整的集成测试,一般建议使用您的实际生产数据库,为您提供最佳的测试保真度 - the EF Core docs提供这方面的详细信息。否则,对于单元测试,您可以有一个存储库抽象并对其进行模拟,在这种情况下,您根本不需要使用 EF Core。

关于c# - Entity Framework Core - 复杂类型映射为 postgres 中的 jsonb 列,但 InMemory 提供程序的映射失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65426317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com