Skip to content

TargetInvocationException when using Contains with nullable value types with HasConversion #3842

@henriquewr

Description

@henriquewr

An exception occurs when using Contains with nullable value types with HasConversion

This error only seems to occurs in the postgresql provider of EfCore

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

MissingMethodException: Constructor on type 'Microsoft.EntityFrameworkCore.Storage.Json.JsonCollectionOfNullableStructsReaderWriter2[[System.Nullable1[[System.Int32, System.Private.CoreLib, Version=10.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]][], System.Private.CoreLib, Version=10.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=10.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' not found.

repro:

public static async Task Main(string[] args)
{
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseNpgsql()
        .Options;

    int?[] numbers = new int?[] { 1, 2, null };

    using var context = new AppDbContext(options);

    var result = await context.Entities.Where(x => numbers.Contains(x.Num)).ToListAsync();
}

public class AppDbContext(DbContextOptions options) : DbContext(options)
{
    public DbSet<SomeEntity> Entities { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.Entity<SomeEntity>().Property(s => s.Num)
            .HasConversion(
                v => v.HasValue ? v.Value.ToString().ToLower() : null,
                v => v == null ? null : int.Parse(v));

    public class SomeEntity
    {
        public int Id { get; set; }
        public int? Num { get; set; }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions