diff --git a/src/EFCore.PG/Query/NpgsqlSqlExpressionFactory.cs b/src/EFCore.PG/Query/NpgsqlSqlExpressionFactory.cs index 3fd39ac8c..4b983270b 100644 --- a/src/EFCore.PG/Query/NpgsqlSqlExpressionFactory.cs +++ b/src/EFCore.PG/Query/NpgsqlSqlExpressionFactory.cs @@ -816,10 +816,27 @@ when left.Type.FullName is "NodaTime.Instant" or "NodaTime.LocalDateTime" or "No $"Incorrect {nameof(operatorType)} for {nameof(pgBinaryExpression)}: {operatorType}"); } + // Preserve the element converter and store type, but give each operand a converter for its own CLR collection type. + // Other concrete collection parameters are materialized to List before conversion in EF8; keep their existing mapping. + // Converter-free mappings can keep using the original array/list parameter without copying. return new PgBinaryExpression( operatorType, - ApplyTypeMapping(left, inferredTypeMapping), - ApplyTypeMapping(right, inferredTypeMapping), + ApplyTypeMapping( + left, + inferredTypeMapping is NpgsqlArrayTypeMapping { Converter: not null } leftArrayMapping + && left.Type != leftArrayMapping.ClrType + && (left.Type.IsArrayOrGenericList() || left.Type.IsInterface) + ? _typeMappingSource.FindCollectionMapping( + leftArrayMapping.StoreType, left.Type, leftArrayMapping.ElementTypeMapping) + : inferredTypeMapping), + ApplyTypeMapping( + right, + inferredTypeMapping is NpgsqlArrayTypeMapping { Converter: not null } rightArrayMapping + && right.Type != rightArrayMapping.ClrType + && (right.Type.IsArrayOrGenericList() || right.Type.IsInterface) + ? _typeMappingSource.FindCollectionMapping( + rightArrayMapping.StoreType, right.Type, rightArrayMapping.ElementTypeMapping) + : inferredTypeMapping), resultType, resultTypeMapping ?? _typeMappingSource.FindMapping(resultType)); diff --git a/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs b/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs index 120898a27..b74e74313 100644 --- a/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs +++ b/src/EFCore.PG/Storage/Internal/NpgsqlTypeMappingSource.cs @@ -577,6 +577,15 @@ is PropertyInfo globalEnumTypeMappingsProperty return null; } + /// + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// + internal RelationalTypeMapping? FindCollectionMapping(string storeType, Type modelType, RelationalTypeMapping elementMapping) + => FindCollectionMapping(new RelationalTypeMappingInfo(modelType, storeTypeName: storeType), modelType, null, elementMapping); + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/test/EFCore.PG.FunctionalTests/Query/ArrayArrayQueryTest.cs b/test/EFCore.PG.FunctionalTests/Query/ArrayArrayQueryTest.cs index fcf3acf8a..f16f27aff 100644 --- a/test/EFCore.PG.FunctionalTests/Query/ArrayArrayQueryTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/ArrayArrayQueryTest.cs @@ -831,6 +831,45 @@ WHERE s."ValueConvertedArrayOfEnum" && @__list_0 """); } + [ConditionalTheory] + [InlineData(false)] + [InlineData(true)] + public virtual async Task Intersect_any_without_converter_does_not_copy_parameter(bool list) + { + await using var context = CreateContext(); + IEnumerable values = list ? new List { 3 } : new[] { 3 }; + + var query = context.SomeEntities.Where(e => e.IntArray.Intersect(values).Any()).Select(e => e.Id); + var reversed = context.SomeEntities.Where(e => values.Intersect(e.IntArray).Any()).Select(e => e.Id); + + using var command = query.CreateDbCommand(); + using var reversedCommand = reversed.CreateDbCommand(); + Assert.Same(values, command.Parameters[0].Value); + Assert.Same(values, reversedCommand.Parameters[0].Value); + + var result = await query.ToArrayAsync(); + var reversedResult = await reversed.ToArrayAsync(); + Assert.Equal([1], result); + Assert.Equal([1], reversedResult); + + AssertSql( + """ +@__values_0={ '3' } (DbType = Object) + +SELECT s."Id" +FROM "SomeEntities" AS s +WHERE s."IntArray" && @__values_0 +""", + // + """ +@__values_0={ '3' } (DbType = Object) + +SELECT s."Id" +FROM "SomeEntities" AS s +WHERE @__values_0 && s."IntArray" +"""); + } + public override async Task All_Contains(bool async) { await base.All_Contains(async); diff --git a/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs index 8dbc71b69..11efa664f 100644 --- a/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs @@ -1,3 +1,4 @@ +using System.Collections.Immutable; using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities; @@ -148,6 +149,195 @@ public class Order } } + [ConditionalTheory] + [InlineData(nameof(Context3805.Entity.Array), "array")] + [InlineData(nameof(Context3805.Entity.Array), "list")] + [InlineData(nameof(Context3805.Entity.Array), "immutable")] + [InlineData(nameof(Context3805.Entity.Array), "set")] + [InlineData(nameof(Context3805.Entity.Array), "enumerable")] + [InlineData(nameof(Context3805.Entity.List), "array")] + [InlineData(nameof(Context3805.Entity.List), "list")] + [InlineData(nameof(Context3805.Entity.List), "immutable")] + [InlineData(nameof(Context3805.Entity.List), "set")] + [InlineData(nameof(Context3805.Entity.List), "enumerable")] + public virtual async Task Intersect_any_with_element_converter_and_different_collection_types( + string propertyName, + string parameterType) + { + var contextFactory = await InitializeAsync( + seed: context => context.Database.ExecuteSqlRaw( + """ +INSERT INTO "Entities" ("Id", "Array", "List") +VALUES (1, ARRAY[42]::bigint[], ARRAY[42]::bigint[]), + (2, ARRAY[99]::bigint[], ARRAY[99]::bigint[]), + (3, ARRAY[]::bigint[], ARRAY[]::bigint[]) +""")); + + await using var context = contextFactory.CreateContext(); + + IEnumerable values = parameterType switch + { + "array" => new Context3805.WrappedId[] { new(42) }, + "list" => new List { new(42) }, + "immutable" => ImmutableList.Create(new Context3805.WrappedId(42)), + "set" => new HashSet { new(42) }, + "enumerable" => new[] { new Context3805.WrappedId(42) }.Where(_ => true), + _ => throw new ArgumentOutOfRangeException(nameof(parameterType)) + }; + + var result = await context.Entities + .Where(e => EF.Property>(e, propertyName).Intersect(values).Any()) + .Select(e => e.Id).ToArrayAsync(); + var reversed = await context.Entities + .Where(e => values.Intersect(EF.Property>(e, propertyName)).Any()) + .Select(e => e.Id).ToArrayAsync(); + + Assert.Equal([1], result); + Assert.Equal([1], reversed); + + AssertSql( + $$""" +@__values_0={ '42' } (DbType = Object) + +SELECT e."Id" +FROM "Entities" AS e +WHERE e."{{propertyName}}" && @__values_0 +""", + // + $$""" +@__values_0={ '42' } (DbType = Object) + +SELECT e."Id" +FROM "Entities" AS e +WHERE @__values_0 && e."{{propertyName}}" +"""); + } + + [ConditionalFact] + public virtual async Task Intersect_any_with_element_converter_and_concrete_immutable_list_parameter() + { + var contextFactory = await InitializeAsync( + seed: context => context.Database.ExecuteSqlRaw( + """ +INSERT INTO "Entities" ("Id", "Array", "List") +VALUES (1, ARRAY[42]::bigint[], ARRAY[42]::bigint[]), + (2, ARRAY[99]::bigint[], ARRAY[99]::bigint[]), + (3, ARRAY[]::bigint[], ARRAY[]::bigint[]) +""")); + + await using var context = contextFactory.CreateContext(); + var values = ImmutableList.Create(new Context3805.WrappedId(42)); + + var result = await context.Entities.Where(e => e.List.Intersect(values).Any()).Select(e => e.Id).ToArrayAsync(); + var reversed = await context.Entities.Where(e => values.Intersect(e.List).Any()).Select(e => e.Id).ToArrayAsync(); + + Assert.Equal([1], result); + Assert.Equal([1], reversed); + + AssertSql( + """ +@__values_0={ '42' } (DbType = Object) + +SELECT e."Id" +FROM "Entities" AS e +WHERE e."List" && @__values_0 +""", + // + """ +@__values_0={ '42' } (DbType = Object) + +SELECT e."Id" +FROM "Entities" AS e +WHERE @__values_0 && e."List" +"""); + } + + protected class Context3805(DbContextOptions options) : DbContext(options) + { + public DbSet Entities => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().PrimitiveCollection(e => e.Array).ElementType().HasConversion(); + modelBuilder.Entity().PrimitiveCollection(e => e.List).ElementType().HasConversion(); + } + + public class Entity + { + public int Id { get; set; } + public WrappedId[] Array { get; set; } = []; + public List List { get; set; } = []; + } + + public readonly record struct WrappedId(long Value); + + private class WrappedIdConverter() : ValueConverter(v => v.Value, v => new WrappedId(v)); + } + + [ConditionalTheory] + [InlineData(nameof(Context3805Ranges.Entity.Ranges))] + [InlineData(nameof(Context3805Ranges.Entity.RangeList))] + public virtual async Task Intersect_any_with_range_array_and_list_parameter(string propertyName) + { + var contextFactory = await InitializeAsync( + seed: context => + { + context.Entities.AddRange( + new Context3805Ranges.Entity { Id = 1, Ranges = [new(1, true, 5, false)], RangeList = [new(1, true, 5, false)] }, + new Context3805Ranges.Entity { Id = 2, Ranges = [new(10, true, 15, false)], RangeList = [new(10, true, 15, false)] }, + new Context3805Ranges.Entity { Id = 3, Ranges = [], RangeList = [] }); + context.SaveChanges(); + }); + + await using var context = contextFactory.CreateContext(); + List> ranges = [new(1, true, 5, false)]; + + var result = await context.Entities + .Where(e => EF.Property>>(e, propertyName).Intersect(ranges).Any()) + .Select(e => e.Id).ToArrayAsync(); + var reversed = await context.Entities + .Where(e => ranges.Intersect(EF.Property>>(e, propertyName)).Any()) + .Select(e => e.Id).ToArrayAsync(); + + Assert.Equal([1], result); + Assert.Equal([1], reversed); + + AssertSql( + $$""" +@__ranges_0={ '[1,5)' } (DbType = Object) + +SELECT e."Id" +FROM "Entities" AS e +WHERE e."{{propertyName}}" && @__ranges_0 +""", + // + $$""" +@__ranges_0={ '[1,5)' } (DbType = Object) + +SELECT e."Id" +FROM "Entities" AS e +WHERE @__ranges_0 && e."{{propertyName}}" +"""); + } + + protected class Context3805Ranges(DbContextOptions options) : DbContext(options) + { + public DbSet Entities => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().PrimitiveCollection(e => e.Ranges).HasColumnType("int4range[]"); + modelBuilder.Entity().PrimitiveCollection(e => e.RangeList).HasColumnType("int4range[]"); + } + + public class Entity + { + public int Id { get; set; } + public NpgsqlRange[] Ranges { get; set; } = []; + public IList> RangeList { get; set; } = []; + } + } + protected override ITestStoreFactory TestStoreFactory => NpgsqlTestStoreFactory.Instance; }