Skip to content

object[]/List<object> Contains over a value-converted column throws in NpgsqlArrayConverter #3916

Closed

Description

@Dreamescaper

Contains over an object[]/List<object> parameter against a column with an element value converter throws at query compilation:

System.ArgumentException: Expression of type 'System.Object' cannot be used for parameter of type 'System.Int32' (Parameter 'arg0')
   at System.Linq.Expressions.Expression.Invoke(Expression expression, Expression arg0)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.ValueConversion.NpgsqlArrayConverter`3.ArrayConversionExpression[TInput,TOutput,TConcreteOutput](LambdaExpression elementConversionExpression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.ValueConversion.NpgsqlArrayConverter`3..ctor(ValueConverter elementConverter)
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Constructor(...)

(TargetInvocationException wrapping the ArgumentException when the converter is constructed reflectively.)

Repro

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

var ids = new object[] { 1, 2 };          // also List<object> { 1, 2 }
using var ctx = new Ctx();
ctx.Blogs.Where(b => ids.Contains(b.Id)).ToQueryString();

sealed class Blog { public int Id { get; set; } }

sealed class Ctx : DbContext
{
    public DbSet<Blog> Blogs => Set<Blog>();
    protected override void OnConfiguring(DbContextOptionsBuilder b)
        => b.UseNpgsql("Host=localhost;Database=x;Username=u");
    protected override void OnModelCreating(ModelBuilder b)
        => b.Entity<Blog>().Property(x => x.Id)
            .HasConversion(new ValueConverter<int, long>(v => v, v => checked((int)v)))
            .HasColumnType("bigint");
}

Results with 10.0.3:

object[]       TargetInvocationException: ArgumentException: Expression of type 'System.Object' cannot be used for parameter of type 'System.Int32' (Parameter 'arg0')
List<object>   TargetInvocationException: ArgumentException: ...
int[]          OK
List<int>      OK

So only collections whose element type (object) differs from the converter's model type (int) fail; typed collections work.

Analysis

NpgsqlArrayTypeMapping.CreateParameters sees the element mapping's converter (int → long) and builds:

NpgsqlArrayConverter<object[], object[], long[]>(elementConverter: ValueConverter<int, long>)

NpgsqlArrayConverter.ArrayConversionExpression then does, in the indexer/for-loop path:

Invoke(elementConversionExpression, indexer(counter))

where indexer(counter) has the collection's element type (object), while the lambda's parameter is the converter's model type (int) — so Expression.Invoke rejects it. The nullable guard above only handles Nullable<T> input/output element types; the object (non-nullable, non-matching) case falls through. It would need to Convert/Unbox the element to elementConversionExpression.Parameters[0].Type before invoking (and the model-type validation in the ctor would need to tolerate the wider collection element type).

This looks like the same family as #2189 / #3050, but for an element type that is wider than the converter's model type rather than nullable.

Environment

  • Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3 (also reproduces on 9.x per the closely-related reports)
  • EF Core 10.0.12, net10.0

Workaround: use a typed collection (int[] / List<int>).

(Found while building an EF Core provider for Aurora DSQL, which widens int identity keys to bigint with exactly this converter; the four failing tests are upstream of that provider.)

Activity

  1. sanjaysingh commented on Oct 14, 2026

    @sanjaysingh
    Contributor

    I was able to reproduce this with both an object[] and a List. I have a PR ready that addresses it: #3961

  2. added theissue type on Oct 15, 2026
  3. roji commented on Oct 15, 2026

    @roji
    Member

    AI Triage

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

    Confirmed PostgreSQL-provider bug. Both object[] and List<object> reproduce the reported TargetInvocationException, with the inner exception:

    Expression of type 'System.Object' cannot be used for parameter of type 'System.Int32' (Parameter 'arg0')
    

    ToQueryString() alone triggers the failure; no database connection, schema, or seed data is required. The issue has been classified as Bug.

    Versions and regression status

    Npgsql.EntityFrameworkCore.PostgreSQL EF Core object[] / List<object>
    8.0.0 8.0.0 Reported exception
    8.0.11 8.0.32 Reported exception
    9.0.4 9.0.21 Reported exception
    10.0.2 10.0.12 Reported exception
    10.0.3 10.0.12 Reported exception
    10.0.3 10.0.13 Reported exception

    This is not a new regression in 10.0.3: the same exception is present in 8.0.0. Npgsql 7.0.18 / EF Core 7.0.20 also fails for both collection types, but with InvalidCastException: Object must implement IConvertible. No previously working version was identified, so an exact regression boundary cannot be established.

    Comparisons ran on .NET 10. C# 12 was used for the historical comparisons to keep Contains bound to the enumerable overload rather than newer span overloads. The reported 10.0.3 failure was also reproduced with the SDK's default language version. The 11.0 prereleases were not tested.

    With Microsoft.EntityFrameworkCore.SqlServer 10.0.12, both object-typed collections translate successfully, including conversion of each parameter to bigint:

    DECLARE @ids1 bigint = CAST(1 AS bigint);
    DECLARE @ids2 bigint = CAST(2 AS bigint);
    
    SELECT [b].[Id]
    FROM [Blogs] AS [b]
    WHERE [b].[Id] IN (@ids1, @ids2)

    This comparison concerns SQL generation, not database execution. It supports keeping this report in the PostgreSQL provider repository.

    Cause and related reports

    The collection element type is object, while the element converter accepts int. NpgsqlArrayConverter invokes that converter with the collection element without inserting the required cast/unboxing. Expression.Invoke therefore rejects the expression. The constructor also validates that the collection's model element type matches the converter's model type, so adapting the invocation alone would not be sufficient.

    PR #3961 already targets this issue.

    Related provider reports are #3919 (non-nullable collection versus nullable converter parameter), #2189 (nullable element conversion), and #3050 (non-instantiable collection types). They involve the same converter machinery but are not exact duplicates of this object/int mismatch.

    I searched open and closed EF Core issues. The closest candidates are:

    • dotnet/efcore#20624: historical List<object>.Contains failure with scalar keys, but without an element value converter and with a different exception.
    • dotnet/efcore#33928: List<object>.Contains over entities, rather than converted scalar values.
    • dotnet/efcore#32376: Contains with a custom converter, but involving SQL Server char conversion and JSON serialization.

    No exact EF Core duplicate was identified.

    Workaround and minimal reproduction

    Verified on Npgsql 10.0.3 / EF Core 10.0.12: changing the collection to either int[] or List<int> allows SQL generation and produces WHERE b."Id" = ANY (@ids).

    Create a console application targeting net10.0, referencing Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3 and Microsoft.EntityFrameworkCore 10.0.12. The following reproduces the reported exception without connecting to PostgreSQL:

    minimal repro
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
    using Microsoft.Extensions.Logging;
    
    var ids = new object[] { 1, 2 };
    using var ctx = new Ctx();
    ctx.Blogs.Where(b => ids.Contains(b.Id)).ToQueryString();
    
    sealed class Blog
    {
        public int Id { get; set; }
    }
    
    sealed class Ctx : DbContext
    {
        public DbSet<Blog> Blogs => Set<Blog>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder b)
            => b
                .UseNpgsql("Host=localhost;Database=repro3916;Username=npgsql_tests")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder b)
            => b.Entity<Blog>().Property(x => x.Id)
                .HasConversion(new ValueConverter<int, long>(v => v, v => checked((int)v)))
                .HasColumnType("bigint");
    }
  4. added this to the 10.0.4 milestone on Oct 16, 2026
  5. added 4 commits that reference this issue on Oct 16, 2026
    a443c5f
    c3d2e3f
    a603fed
    4430302
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions