Skip to content

Unable to cast object of type 'System.Double[]' to type 'System.Double[,]' for empty values in 'double precision multi dimensional array' #3514

Closed as duplicate

Description

@dkezri

This happens when we upgrade from dotnet version 8.0 to 9.0

We have a table column of type "double precision two dimensional array", when we add a record with an empty value, it will be recorded as '{}' in the database which can not be converted back from database to a two dimensional array and it fails with the exception in the title. It looks like it treats the empty values in the column as one dimensional array. If we make the column nullable then it works fine.

using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

public class Vertex
{
    public double X { get; set; }
    public double Y { get; set; }
}

 public class VertexConfig : IEntityTypeConfiguration<Vertex>
 {

        public void Configure(EntityTypeBuilder<Vertex> entity)
        {
            entity.Property(e => e.Vertex)
            .HasColumnName("Vertex")
            .HasConversion(new VertexesConverter());
        }
 }

public class VertexesConverter : ValueConverter<List<Vertex>, double[,]>
{
    public VertexesConverter() : base(
        v => ConvertToDatabase(v),
        v => ConvertFromDatabase(v))
    {
    }

    private static double[,] ConvertToDatabase(List<Vertex> Vertexes)
    {
        if (Vertexes == null || Vertexes.Count == 0)
        {
            return new double[0, 0]; // Empty 2D array
        }

        var array = new double[Vertexes.Count, 2];
        for (int i = 0; i < Vertexes.Count; i++)
        {
            array[i, 0] = Vertexes[i].X;
            array[i, 1] = Vertexes[i].Y;
        }
        return array;
    }

    private static List<Vertex> ConvertFromDatabase(double[,] data)
    {
        if (data.GetLength(0) == 0)
        {
            return new List<Vertex>(); // Handle empty 2D array
        }

        var Vertexes = new List<Vertex>();
        for (int i = 0; i < data.GetLength(0); i++)
        {
            Vertexes.Add(new Vertex { X = data[i, 0], Y = data[i, 1] });
        }
        return Vertexes;
    }
}



Activity

  1. changed the title [-]Unable to cast object of type 'System.Double[]' to type 'System.Double[,]'[/-] [+]Unable to cast object of type 'System.Double[]' to type 'System.Double[,]' for empty values in 'double precision multi dimensional array'[/+] on Apr 1, 2025
  2. transferred this issue fromnpgsql/npgsqlon Apr 1, 2025
  3. dkezri commented on Apr 7, 2025

    @dkezri
    Author

    Hi @vonzshik any progress on this issue?

  4. vonzshik commented on Apr 7, 2025

    @vonzshik
    Contributor

    I only work on Npgsql, so, uh, nothing from me.

  5. roji commented on Apr 7, 2025

    @roji
    Member

    It will unfortunately be a while before I can investigate this.

  6. added theissue type on Oct 18, 2026
  7. roji commented on Oct 18, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed bug and regression from Npgsql 8 to 9. The reported List<Vertex>/VertexesConverter scenario reproduces with provider 9.0.0, but neither the converter nor EF is necessary: reading an empty PostgreSQL array directly with NpgsqlDataReader.GetFieldValue<double[,]>() produces the same exception. This belongs in the Npgsql ADO.NET driver rather than EF Core's general query/materialization code.

    Version comparison

    The following reduced EF round-trip was tested against PostgreSQL 18.4, keeping the runtime fixed at .NET 10.0.8 to isolate package-version differences:

    EF PostgreSQL provider EF Core Npgsql Empty double[,]
    8.0.11 8.0.11 8.0.6 Succeeds
    9.0.0 9.0.0 9.0.0 InvalidCastException
    9.0.4 9.0.1 9.0.3 Same exception
    10.0.3 10.0.4 10.0.3 Same exception

    A nonempty double[,] { { 1, 2 } } round-trips successfully in all four cases. Direct ADO.NET reads also succeed with Npgsql 7.0.0, 7.0.10, 8.0.0 and 8.0.9, and fail with 9.0.0, 9.0.5 and 10.0.3. Upgrading to the tested newer releases does not resolve it.

    minimal repro

    EF repro, referencing Npgsql.EntityFrameworkCore.PostgreSQL 9.0.0; switch the package to 8.0.11 to see the successful behavior. Set Test__Npgsql__DefaultConnection to a disposable test database, since this program deletes and recreates it.

    using System;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    await using var context = new TestContext();
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();
    context.Add(new Blog());
    await context.SaveChangesAsync();
    context.ChangeTracker.Clear();
    await context.Blogs.SingleAsync();
    
    public class TestContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"))
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public double[,] Vertex { get; set; } = new double[0, 0];
    }

    Smaller repro requiring only the Npgsql package, with no EF dependency or database modifications:

    using System;
    using Npgsql;
    
    await using var connection = new NpgsqlConnection(
        Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"));
    await connection.OpenAsync();
    await using var command = new NpgsqlCommand("SELECT '{}'::double precision[]", connection);
    await using var reader = await command.ExecuteReaderAsync();
    await reader.ReadAsync();
    reader.GetFieldValue<double[,]>(0);

    On Npgsql 9.0.0, 9.0.5 and 10.0.3:

    System.InvalidCastException: Unable to cast object of type 'System.Double[]' to type 'System.Double[,]'.
       at Npgsql.NpgsqlDataReader.GetFieldValueCore[T](Int32 ordinal)
       at Npgsql.NpgsqlDataReader.GetFieldValue[T](Int32 ordinal)
    

    Cause and ownership

    PostgreSQL represents an empty array with zero dimensions. Npgsql 8 nevertheless allocates the result using the requested CLR rank: new int[_expectedDimensions ?? dimensions]. For GetFieldValue<double[,]>(), this produces the appropriate empty two-dimensional array.

    npgsql/npgsql#5736 replaced that logic with a slice based solely on the dimensions received from PostgreSQL. The changed logic remains in Npgsql 10.0.3. For an empty array, that slice has length zero, and CreateCollection returns Array.Empty<TElement?>(): a one-dimensional array, causing the cast failure.

    The fix should restore the requested CLR rank for zero-dimensional PostgreSQL arrays in the driver, with coverage for empty multidimensional reads. This is PostgreSQL/Npgsql-specific, not a general EF regression. As a cross-provider check, SQLite rejects the same double[,] property during model validation because it has no native mapping; it does not reach the failing array-read path.

    Related reports

    • npgsql/npgsql#1271 reports the same historical symptom. Support for reading empty multidimensional arrays was subsequently added in npgsql/npgsql#2916; this is a regression of that behavior.
    • npgsql/efcore.pg#314 tracks broader multidimensional-array support, but this specific read regression can be reproduced and fixed independently of EF.
    • dotnet/efcore#26975 concerns a different, fixed EF 5-to-6 value-comparer/model-initialization regression, not this empty-array read failure. No matching duplicate was found in the EF Core issue search.

    Recommendation: track the fix in npgsql/npgsql; the converter does not need to be changed to explain or reproduce this failure.

  8. roji commented on Oct 18, 2026

    @roji
    Member

    Duplicate of npgsql/npgsql#6675. The failure is in the Npgsql ADO.NET driver and reproduces without EF Core; the repro and regression analysis are tracked there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions