How can I read an array of custom type using Npgsql?

I want to read a custom type array, but Npgsql throws an exception: 'Reading as 'TestVariant[]' is not supported for fields having DataTypeName 'public.testvariant[]"

Simplified query:

const string Sql = """
    SELECT
        array_agg(t)
    FROM
        TestVariant t;
    """;

using var command = new NpgsqlCommand(Sql, _connection);

using var reader = command.ExecuteReader();

reader.Read();

var test = reader.GetFieldValue<TestVariant[]>(0);

Type:

public class TestVariant
{
    public Guid Id { get; set; }
    public string Text { get; set; }
    public DateTime AddedAt { get; set; }
}

  • Do you have a PG composite type defined, correpsonding to your TestVariant? Have you mapped TestVariant as described in the docs? In general, always post an actual runnable and minimal console program, rather than partial snippets which don’t fully show what you’re doing.

    – 

Leave a Comment