[英]How to read an enum array from Postgres into a list of enums in C#?
net core 6.0 application using Npgsql v6.0.4.使用 Npgsql v6.0.4 的 net core 6.0 应用程序。
Table:桌子:
CREATE TABLE kontrolle.negativtext (
id serial NOT NULL,
check_doc "_negative_doc_check" NULL DEFAULT
CONSTRAINT negativtext_pkey PRIMARY KEY (id)
);
Column check_doc
is an array of the custom enum type _negative_doc_check
.列
check_doc
是自定义枚举类型_negative_doc_check
的数组。
Enum:枚举:
select enum_range(null::negative_doc_check)
returns {CONTENT_HTML_DIRTY,CONTENT_HTML_CLEAN,CONTENT_TXT_DIRTY,CONTENT_TXT_CLEAN}
返回
{CONTENT_HTML_DIRTY,CONTENT_HTML_CLEAN,CONTENT_TXT_DIRTY,CONTENT_TXT_CLEAN}
Code:代码:
using System;
using System.Collections.Generic;
using Npgsql;
var constring = "SERVER=192.168.2.121;DATABASE=myuser;USER ID=mydb;PASSWORD=mypasswd;";
NpgsqlConnection.GlobalTypeMapper.MapEnum<negative_doc_check>("negative_doc_check");
await using var conn = new NpgsqlConnection(constring);
await conn.OpenAsync();
await using (var cmd = new NpgsqlCommand("SELECT check_doc from kontrolle.negativtext where id = 643", conn))
await using (var reader = await cmd.ExecuteReaderAsync()) {
while (await reader.ReadAsync()) {
var enumValue = reader.GetFieldValue<List<negative_doc_check>>(0);
Console.WriteLine(enumValue);
}
}
public enum negative_doc_check {
CONTENT_HTML_DIRTY = 0,
CONTENT_HTML_CLEAN = 1,
CONTENT_TXT_DIRTY = 2,
CONTENT_TXT_CLEAN = 4
}
public class Negativtext {
public int Id { get; set; }
public List<negative_doc_check> CheckDoc { get; set; }
}
Exception:例外:
System.InvalidCastException: "Received enum value 'CONTENT_TXT_DIRTY' from database which wasn't found on enum negative_doc_check"
The enum values are identical in both my C# code and the Postgres type definition.我的 C# 代码和 Postgres 类型定义中的枚举值是相同的。 Am I missing something or is it just not possible to read a list of enums ?
我是否遗漏了什么,或者只是无法阅读枚举列表?
By default, when mapping .NET to PG enums, Npgsql assumes .NET enums are named like standard .NET types (Pascal Case, ie NativeDocCheck and not negative_doc_check), whereas your PG enums are assumed to be snake case (ie negative_doc_check).默认情况下,当将 .NET 映射到 PG 枚举时,Npgsql 假定 .NET 枚举被命名为标准 .NET 类型(Pascal Case,即 NativeDocCheck 而不是negative_doc_check),而您的 PG 枚举被假定为蛇案例(即negative_doc_check)。 It's recommended to change your .NET enum to conform to that:
建议更改您的 .NET 枚举以符合以下要求:
public enum NegativeDocCheck {
ContentHtmlDirty = 0,
ContentHtmlClean = 1,
ContentTxtDirty = 2,
ContentTxtClean = 4
}
Otherwise, to keep your non-standard naming, you can tell Npgsql to map the names as is when mapping the enum:否则,为了保持您的非标准命名,您可以告诉 Npgsql 在映射枚举时按原样映射名称:
NpgsqlConnection.GlobalTypeMapper.MapEnum<negative_doc_check>("negative_doc_check", new NpgsqlNullNameTranslator());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.