我在使用postgres枚举时遇到了一个奇怪的问题,在try 查询一个带有ENUM
的表时出现错误,但前提是在同一会话中运行了CREATE
命令.我不知道为什么会发生这种情况,这使得运行迁移脚本变得非常困难,因为我现在必须运行应用程序两次才能正常工作.
我认为这是某种缓存问题,我try 关闭连接池,但似乎也不起作用.
它很容易重现,所以我制作了一个代码样本:
using Dapper;
using Npgsql;
var connection = new NpgsqlConnection("Host=127.0.0.1;Port=5432;User ID=postgres;Password=password;Database=messaging;Include Error Detail=true;");
await connection.OpenAsync();
var tableCommand = new NpgsqlCommand()
{
Connection = connection,
CommandText = """
CREATE TYPE message_type AS ENUM ('sms', 'email');
CREATE TABLE message (
id SERIAL PRIMARY KEY,
type message_type NOT NULL
);
"""
};
// Comment this line on a second run
await tableCommand.ExecuteNonQueryAsync();
var queryCommand = new NpgsqlCommand()
{
Connection = connection,
CommandText = """
SELECT id, type
FROM message;
"""
};
var reader = await queryCommand.ExecuteReaderAsync();
// The offending line
var parser = reader.GetRowParser<Message>();
class Message
{
public int Id { get; set; }
public string? Type { get; set; }
}
这将在第一次运行时产生以下错误:
System.InvalidCastException: 'Reading as 'System.Object' is not supported for fields having DataTypeName '.<unknown>''
Inner Exception
ArgumentException: A PostgreSQL type with the oid '0' was not found in the current database info
在第二次运行时(在注释掉CREATE命令时),我没有收到任何错误,一切都按预期运行.它似乎在第一次运行时看不到枚举存在,但在第二次运行时一切正常,因为建立连接时它已经在那里了.
我正在使用所有内容的最新版本(在 compose 本文时):
- Postgres 16.1
- .NET 8
- Dapper是2.1.24.
- Npgsql 8.0.1