我在postgre数据库中定义了以下复合类型:
CREATE TYPE foobar AS
(
foo NUMERIC,
bar NUMERIC
);
我创建了具有相同属性的结构:
public struct FooBar
{
public decimal Foo { get; set; }
public decimal Bar { get; set; }
}
现在我想在实体中像这样使用FooBar:
public class FooyaEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public FooBar FooBar { get; set; }
}
我将如何配置ef core以正确映射它们?当前,当尝试添加某些内容时会产生以下错误:
System.InvalidOperationException:无法映射属性'Test.FooBar',因为它的类型为'FooBar',它不是受支持的原始类型或有效实体类型。显式映射此属性,或使用'[NotMapped]'属性或'OnModelCreating'中的'EntityTypeBuilder.Ignore'忽略它。
而且documentation for npgsql显示了没有ef核心的工作示例。
尝试在您的上下文类上重写OnModelCreating
方法,并执行以下操作:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasPostgresEnum<FooBar>();
}
还为您的上下文添加静态构造函数:
static MyDbContext()
=> NpgsqlConnection.GlobalTypeMapper.MapEnum<FooBar>();
此代码使Npgsql知道您的CLR枚举类型FooBar
应该映射到名为Foobar
的数据库枚举。您可以在此link]上找到更多信息
尚不支持映射到PostgreSQL复合类型,this is tracked by this issue。任何有兴趣的人,请投票!