Skip to content

NpgsqlArrayConverter.ArrayConversionExpression throws IndexOutOfRangeException when using a custom derived type for the collection #3092

@PressXtoChris

Description

@PressXtoChris

When using a custom derived class for a collection, the ArrayConversionExpression method throws an IndexOutOfRangeException when it attempts to get the (missing) generic type argument.

var iListType = typeof(IList<>).MakeGenericType(typeof(TInput).GetGenericArguments()[0]);

Example use case:

public class TestEntity(Guid id, CustomCollection values)
{
    public Guid Id { get; } = id;
    public CustomCollection Values { get; } = values;
}

public class CustomCollection : ReadOnlyCollection<string>
{
    public CustomCollection(string[] strings) : base(strings)
    {
        if (strings.Length == 0)
            throw new ArgumentException("At least one string must be provided", nameof(strings));
    }

    public bool SomeBusinessLogic() => this.Any(s => s.Contains("foo"));
}

public class TestDbContext : DbContext
{
    public DbSet<TestEntity> TestEntities { get; set; } = default!;
    public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestEntity>()
            .ToTable("test_entities");

        modelBuilder.Entity<TestEntity>()
            .Property(x => x.Id)
            .HasColumnName("id");

        modelBuilder.Entity<TestEntity>()
            .PrimitiveCollection(x => x.Values)
            .HasColumnName("values")
            .ElementType()
            .HasConversion(typeof(CustomCollectionConversion));
    }
}

I think this could be resolved by getting the generic type arguments of the base class if TInput doesn't have any:

typeof(TInput).BaseType.GetGenericArguments()[0]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions