From 2323adba0cc1322dd237bce6054b6728423380ad Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 18 Oct 2026 11:53:47 +0200 Subject: [PATCH] Preserve array element converters with explicit column types Retain element conversion metadata when resolving explicitly typed arrays while preserving column-type precedence. Cover custom enum conversion and explicit integer/bigint element mappings. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c376b6c6-fe3d-412c-819e-f125721cdbaa --- .../Internal/NpgsqlTypeMappingSource.cs | 31 ++++++--- .../ValueConvertersEndToEndNpgsqlTest.cs | 63 +++++++++++++++++++ .../Storage/NpgsqlTypeMappingSourceTest.cs | 23 +++++++ 3 files changed, 110 insertions(+), 7 deletions(-) diff --git a/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs b/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs index 2d9bf1df8..720ccb409 100644 --- a/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs +++ b/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs @@ -461,7 +461,8 @@ public NpgsqlTypeMappingSource( if ((storeTypeName.EndsWith("[]", StringComparison.Ordinal) || storeTypeName is "int4multirange" or "int8multirange" or "nummultirange" or "datemultirange" or "tsmultirange" or "tstzmultirange") - && FindCollectionMapping(mappingInfo, mappingInfo.ClrType, providerType: null, elementMapping: null) is + && FindCollectionMapping( + mappingInfo, mappingInfo.ClrType, providerType: null, elementMapping: mappingInfo.ElementTypeMapping) is RelationalTypeMapping collectionMapping) { return collectionMapping; @@ -660,13 +661,29 @@ public NpgsqlTypeMappingSource( // We have an array store type (either because we're reverse engineering or the user explicitly specified it) var elementStoreType = storeType.Substring(0, storeType.Length - 2); - // Note that we ignore the elementMapping argument here (but not in the CLR type-only path above). - // This is because the user-provided storeType for the array should take precedence over the element type mapping that gets - // calculated purely based on the element's CLR type in base.FindMappingWithConversion. - var relationalElementMapping = elementMapping as RelationalTypeMapping - ?? (elementType is null + // The array's explicit store type takes precedence over the element store type inferred by base.FindMappingWithConversion + // (e.g. int[] explicitly mapped to bigint[]). Reuse the supplied element mapping only if its store type matches. + // However, that mapping can also carry a configured converter, which must not be discarded (#3636). + // When resolving a different store type, use the converter's provider CLR type, then compose the converter onto the + // new mapping and retain its comparers and JSON reader/writer. This preserves convention-selected converters too, + // not just explicitly configured ones, so conversion selection can differ from resolving solely by the element CLR type. + var relationalElementMapping = elementMapping as RelationalTypeMapping; + if (relationalElementMapping?.StoreType != elementStoreType) + { + relationalElementMapping = elementType is null ? FindMapping(elementStoreType) - : FindMapping(elementType, elementStoreType)); + : FindMapping(elementMapping?.Converter?.ProviderClrType ?? elementType, elementStoreType); + + if (relationalElementMapping is not null && elementMapping is not null) + { + relationalElementMapping = (RelationalTypeMapping)relationalElementMapping.WithComposedConverter( + elementMapping.Converter, + elementMapping.Comparer, + elementMapping.KeyComparer, + jsonValueReaderWriter: elementMapping.JsonValueReaderWriter); + } + } + if (relationalElementMapping is not { ElementTypeMapping: null }) { return null; diff --git a/test/EFCore.PG.FunctionalTests/ValueConvertersEndToEndNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/ValueConvertersEndToEndNpgsqlTest.cs index 170740304..9972ba3a4 100644 --- a/test/EFCore.PG.FunctionalTests/ValueConvertersEndToEndNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/ValueConvertersEndToEndNpgsqlTest.cs @@ -167,6 +167,42 @@ public async Task Can_insert_and_read_back_with_value_converted_array() Assert.Equal(9, entity.Values[1].Value); } + [ConditionalTheory] + [InlineData(nameof(ValueConvertedArrayEntity.EnumValues), "text")] + [InlineData(nameof(ValueConvertedArrayEntity.EnumValuesText), "text")] + [InlineData(nameof(ValueConvertedArrayEntity.EnumValuesVarchar), "varchar(16)")] + public async Task Can_insert_and_query_array_with_custom_element_converter(string propertyName, string elementStoreType) + { + await using var context = CreateContext(); + + var entity = new ValueConvertedArrayEntity { Values = [] }; + context.Add(entity); + context.Entry(entity).Property(propertyName).CurrentValue = [SomeEnum.NoValue, SomeEnum.FirstValue]; + await context.SaveChangesAsync(); + + var id = entity.Id; + context.ChangeTracker.Clear(); + + var mapping = context.Model.FindEntityType(typeof(ValueConvertedArrayEntity))! + .FindProperty(propertyName)!.GetRelationalTypeMapping(); + Assert.Equal(elementStoreType, Assert.IsAssignableFrom(mapping.ElementTypeMapping).StoreType); + + var sql = $$""" +SELECT "{{propertyName}}" AS "Value" FROM "ValueConvertedArrayEntity" WHERE "Id" = {0} +"""; + var storedValues = await context.Database.SqlQueryRaw(sql, id).SingleAsync(); + Assert.Equal(["no-value", "first-value"], storedValues); + + var query = context.Set() + .Where(e => e.Id == id && EF.Property(e, propertyName).Contains(SomeEnum.FirstValue)); + Assert.Contains($"""'first-value' = ANY (v."{propertyName}")""", query.ToQueryString()); + + entity = await query.SingleAsync(); + Assert.Equal( + [SomeEnum.NoValue, SomeEnum.FirstValue], + context.Entry(entity).Property(propertyName).CurrentValue); + } + public class ValueConvertersEndToEndNpgsqlFixture : ValueConvertersEndToEndFixtureBase { protected override ITestStoreFactory TestStoreFactory @@ -196,15 +232,42 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity() .PrimitiveCollection(x => x.Values) .ElementType(e => e.HasConversion(typeof(IntWrapperConverter))); + + modelBuilder.Entity() + .PrimitiveCollection(e => e.EnumValues) + .ElementType(e => e.HasConversion()); + + modelBuilder.Entity() + .PrimitiveCollection(e => e.EnumValuesText) + .HasColumnType("text[]") + .ElementType(e => e.HasConversion()); + + modelBuilder.Entity() + .PrimitiveCollection(e => e.EnumValuesVarchar) + .HasColumnType("varchar(16)[]") + .ElementType(e => e.HasConversion()); } private class IntWrapperConverter() : ValueConverter(iw => iw.Value, i => new IntWrapper(i)); + + private class SomeEnumConverter() : ValueConverter( + value => value == SomeEnum.NoValue ? "no-value" : "first-value", + value => value == "no-value" ? SomeEnum.NoValue : SomeEnum.FirstValue); } public class ValueConvertedArrayEntity { public int Id { get; set; } public IntWrapper[] Values { get; set; } = null!; + public SomeEnum[] EnumValues { get; set; } = []; + public SomeEnum[] EnumValuesText { get; set; } = []; + public SomeEnum[] EnumValuesVarchar { get; set; } = []; + } + + public enum SomeEnum + { + NoValue, + FirstValue } public class IntWrapper(int value) : IEquatable diff --git a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs index b1ec3c98b..0d85ce0ab 100644 --- a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs +++ b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs @@ -251,6 +251,29 @@ public void Primitive_collection() Assert.Same(typeof(int[]), mapping.ClrType); } + [Theory] + [InlineData("integer[]", "integer", false)] + [InlineData("integer[]", "integer", true)] + [InlineData("bigint[]", "bigint", false)] + [InlineData("bigint[]", "bigint", true)] + public void Array_property_with_explicit_store_type(string storeType, string elementStoreType, bool useConverter) + { + var collection = CreateModelBuilder().Entity("Entity") + .PrimitiveCollection("Values") + .HasColumnType(storeType); + if (useConverter) + { + collection.ElementType().HasConversion(new ValueConverter(v => v + 1, v => v - 1)); + } + + var mapping = Assert.IsAssignableFrom(CreateTypeMappingSource().FindMapping((IProperty)collection.Metadata)); + + Assert.Equal(storeType, mapping.StoreType); + Assert.Equal(elementStoreType, mapping.ElementTypeMapping.StoreType); + var expectedElements = useConverter ? "2,3" : "1,2"; + Assert.Equal($"ARRAY[{expectedElements}]::{storeType}", mapping.GenerateSqlLiteral(new[] { 1, 2 })); + } + [Fact] public void Array_over_type_mapping_with_value_converter_by_clr_type_array() => Array_over_type_mapping_with_value_converter(CreateTypeMappingSource().FindMapping(typeof(LTree[])), typeof(LTree[]));