【问题标题】:EF Core and PostgreSQL enum two-way name translationEF Core 和 PostgreSQL 枚举双向名称翻译
【发布时间】:2023-02-04 20:23:57
【问题描述】:

我想弄清楚如何在 postgres DB 和 EF Core 之间启用双向名称转换。我找到了一个link,其中告诉我如何将值从 EF Core 转换为 DB,但没有关于从 DB 到 EF Core 的信息。问题是,当我从数据库中读取时,我得到了值蛇案例,但我需要他们帕斯卡案件。

【问题讨论】:

  • 你能发布一些代码来显示什么不起作用吗?

标签: postgresql entity-framework-core npgsql


【解决方案1】:

你是如何从数据库中读取数据的?

如果您正在写入和读入与 postgres 枚举类型相对应的 C# 枚举类型,Npgsql 会负责双向转换值。

例如:

定义你的类型:

public enum SomeDbEnum
{
    FirstValue,
    SecondValue 
}

public class SomeDbObject
{
    public SomeDbEnum DbEnum { get; set; }
}

Map your enum types

protected override void OnModelCreating(ModelBuilder builder)
    => builder.HasPostgresEnum<SomeDbEnum>();
static MyDbContext()
    => NpgsqlConnection.GlobalTypeMapper.MapEnum<SomeDbEnum>();

试试看:

var toWriteToDb = new SomeDbObject { DbEnum = SomeDbEnum.SecondValue };
context.SomeDbObject.Add(toWriteToDb);
// value inserted as "second_value"

var readFromDb = context.SomeDbObject.FirstOrDefault(x => x.DbEnum == SomeDbEnum.SecondValue);
Console.WriteLine(readFromDb.DbEnum);
// value output as SecondValue

即使您使用 something other than the default naming translations,即注册了其他一些 INpgsqlNameTranslator(默认的 NpgsqlSnakeCaseNameTranslator 除外)或使用 PgNameAttribute 装饰您的枚举成员,同样的事情也适用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2022-11-30
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多