Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<SomeEnum[]>(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<RelationalTypeMapping>(mapping.ElementTypeMapping).StoreType);

var sql = $$"""
SELECT "{{propertyName}}" AS "Value" FROM "ValueConvertedArrayEntity" WHERE "Id" = {0}
""";
var storedValues = await context.Database.SqlQueryRaw<string[]>(sql, id).SingleAsync();
Assert.Equal(["no-value", "first-value"], storedValues);

var query = context.Set<ValueConvertedArrayEntity>()
.Where(e => e.Id == id && EF.Property<SomeEnum[]>(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<SomeEnum[]>(propertyName).CurrentValue);
}

public class ValueConvertersEndToEndNpgsqlFixture : ValueConvertersEndToEndFixtureBase
{
protected override ITestStoreFactory TestStoreFactory
Expand Down Expand Up @@ -196,15 +232,42 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con
modelBuilder.Entity<ValueConvertedArrayEntity>()
.PrimitiveCollection(x => x.Values)
.ElementType(e => e.HasConversion(typeof(IntWrapperConverter)));

modelBuilder.Entity<ValueConvertedArrayEntity>()
.PrimitiveCollection(e => e.EnumValues)
.ElementType(e => e.HasConversion<SomeEnumConverter>());

modelBuilder.Entity<ValueConvertedArrayEntity>()
.PrimitiveCollection(e => e.EnumValuesText)
.HasColumnType("text[]")
.ElementType(e => e.HasConversion<SomeEnumConverter>());

modelBuilder.Entity<ValueConvertedArrayEntity>()
.PrimitiveCollection(e => e.EnumValuesVarchar)
.HasColumnType("varchar(16)[]")
.ElementType(e => e.HasConversion<SomeEnumConverter>());
}

private class IntWrapperConverter() : ValueConverter<IntWrapper, int>(iw => iw.Value, i => new IntWrapper(i));

private class SomeEnumConverter() : ValueConverter<SomeEnum, string>(
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<IntWrapper>
Expand Down
23 changes: 23 additions & 0 deletions test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<int[]>("Values")
.HasColumnType(storeType);
if (useConverter)
{
collection.ElementType().HasConversion(new ValueConverter<int, int>(v => v + 1, v => v - 1));
}

var mapping = Assert.IsAssignableFrom<NpgsqlArrayTypeMapping>(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[]));
Expand Down
Loading