From 0060a0f57fbe27fb405c9c77d385678f9a51483f Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 18 Oct 2026 12:18:38 +0200 Subject: [PATCH 1/2] [10.0] Preserve array element converters with explicit column types Backport #4007 to hotfix/10.0.4. Retain element conversion metadata when resolving explicitly typed arrays while preserving column-type precedence. (cherry picked from commit 93579295ac8949ace0898764527edaf2cbc15580) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3c63e161-0531-4e0b-9756-a1eb6f999014 --- .../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 2d9bf1df8f..720ccb4099 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 7fa28f4e15..2ca208eccf 100644 --- a/test/EFCore.PG.FunctionalTests/ValueConvertersEndToEndNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/ValueConvertersEndToEndNpgsqlTest.cs @@ -168,6 +168,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 @@ -192,15 +228,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 2c7233d26a..8c6ff8bb8f 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[])); From 842f9cd372b6b6374db46ea32cac4a3e9855115b Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 18 Oct 2026 13:33:21 +0200 Subject: [PATCH 2/2] Preserve explicit array element JSON mappings Compose converters over the JSON reader/writer selected for the explicit element store type instead of restoring the inferred writer. This prevents timestamp arrays from reverting to timestamptz JSON serialization and breaking the JSON query/update fixtures. Cover timestamp array JSON serialization with and without an element converter. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3c63e161-0531-4e0b-9756-a1eb6f999014 --- .../Internal/NpgsqlTypeMappingSource.cs | 6 +++--- .../Storage/NpgsqlTypeMappingSourceTest.cs | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs b/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs index 720ccb4099..75053c3547 100644 --- a/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs +++ b/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs @@ -665,7 +665,8 @@ public NpgsqlTypeMappingSource( // (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, + // new mapping and retain its comparers. Compose over the new mapping's JSON reader/writer, which can depend on the + // store type (e.g. timestamp vs. timestamptz). 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) @@ -679,8 +680,7 @@ public NpgsqlTypeMappingSource( relationalElementMapping = (RelationalTypeMapping)relationalElementMapping.WithComposedConverter( elementMapping.Converter, elementMapping.Comparer, - elementMapping.KeyComparer, - jsonValueReaderWriter: elementMapping.JsonValueReaderWriter); + elementMapping.KeyComparer); } } diff --git a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs index 8c6ff8bb8f..557102aa7d 100644 --- a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs +++ b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs @@ -274,6 +274,26 @@ public void Array_property_with_explicit_store_type(string storeType, string ele Assert.Equal($"ARRAY[{expectedElements}]::{storeType}", mapping.GenerateSqlLiteral(new[] { 1, 2 })); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Array_property_with_explicit_timestamp_store_type_json(bool useConverter) + { + var collection = CreateModelBuilder().Entity("Entity") + .PrimitiveCollection("Values") + .HasColumnType("timestamp without time zone[]"); + if (useConverter) + { + collection.ElementType().HasConversion(new ValueConverter(v => v.AddDays(1), v => v.AddDays(-1))); + } + + var mapping = Assert.IsAssignableFrom(CreateTypeMappingSource().FindMapping((IProperty)collection.Metadata)); + + Assert.Equal("timestamp without time zone", mapping.ElementTypeMapping.StoreType); + var expectedJson = useConverter ? """["2020-01-03T03:04:05"]""" : """["2020-01-02T03:04:05"]"""; + Assert.Equal(expectedJson, mapping.JsonValueReaderWriter.ToJsonString(new[] { new DateTime(2020, 1, 2, 3, 4, 5) })); + } + [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[]));