Skip to content
Open
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
3 changes: 3 additions & 0 deletions src/EFCore.Relational/EFCore.Relational.baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -15984,6 +15984,9 @@
{
"Member": "static string SelectExpressionNonTphWithCustomTable(object? entityType);"
},
{
"Member": "static string SetOperationOverCollectionsWithIncompatibleElementMappings(object? storeType1, object? storeType2);"
},
{
"Member": "static string SetOperationOverDifferentStructuralTypes(object? type1, object? type2);"
},
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/EFCore.Relational/Properties/RelationalStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1306,6 +1306,9 @@
<data name="SelectExpressionUpdateNotSupportedWhileMutable" xml:space="preserve">
<value>SelectExpression.Update() is not supported while the expression is in mutable state.</value>
</data>
<data name="SetOperationOverCollectionsWithIncompatibleElementMappings" xml:space="preserve">
<value>The primitive collections combined by the set operation have element type mappings that aren't compatible ('{storeType1}' and '{storeType2}'). Use the same element conversion for both collections, or perform the set operation on the elements instead.</value>
</data>
<data name="SetOperationOverDifferentStructuralTypes" xml:space="preserve">
<value>Set operations over different entity or complex types are not supported ('{type1}' and '{type2}').</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,19 @@ private Expression VisitMethodCallCore(MethodCallExpression methodCallExpression

var translated = base.VisitMethodCall(methodCallExpression);

// AsQueryable over a primitive collection column that was projected out of a subquery, e.g. after a set operation (#33258).
// Unlike a property of an entity, it isn't bound by TranslateMemberAccess, so translate the column as a collection here.
if (translated == QueryCompilationContext.NotTranslatedExpression
&& method.IsGenericMethod
&& method.GetGenericMethodDefinition() == QueryableMethods.AsQueryable
&& methodCallExpression.Arguments[0] is not MethodCallExpression // EF.Property etc. are handled by the base class
&& _sqlTranslator.Visit(methodCallExpression.Arguments[0]) is ColumnExpression { TypeMapping.ElementTypeMapping: not null } column
&& TranslatePrimitiveCollection(column, property: null, _sqlAliasManager.GenerateTableAlias(column.Name))
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved
is { } columnCollection)
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved
{
return columnCollection;
}

// For Contains over a collection parameter, if the provider hasn't implemented TranslateCollection (e.g. OPENJSON on SQL
// Server), we need to fall back to the previous IN translation.
if (translated == QueryCompilationContext.NotTranslatedExpression
Expand Down Expand Up @@ -421,7 +434,9 @@ ParameterTranslationMode.Constant or ParameterTranslationMode.MultipleParameters
/// <param name="sqlExpression">The expression to try to translate as a primitive collection expression.</param>
/// <param name="property">
/// If the primitive collection is a property, contains the <see cref="IProperty" /> for that property. Otherwise, the collection
/// represents a parameter, and this contains <see langword="null" />.
/// represents a parameter, or a collection column projected out of a subquery (for example by a set operation), and this
/// contains <see langword="null" />. In the latter case, <paramref name="sqlExpression" /> is a column with a type mapping that has
/// an <see cref="CoreTypeMapping.ElementTypeMapping" />, unlike for a parameter, whose element type mapping is inferred later.
/// </param>
/// <param name="tableAlias">
/// Provides an alias to be used for the table returned from translation, which will represent the collection.
Expand Down
13 changes: 13 additions & 0 deletions src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2399,6 +2399,19 @@ private void ApplySetOperation(
var innerColumn1 = (SqlExpression)expression1;
var innerColumn2 = (SqlExpression)expression2;

// The result takes its type mapping from the first operand, so primitive collections whose elements are stored differently
// (e.g. one with a value converter and one without) would be read, and queried over, using the wrong element mapping (#33258).
if (innerColumn1.TypeMapping?.ElementTypeMapping is RelationalTypeMapping elementTypeMapping1
&& innerColumn2.TypeMapping?.ElementTypeMapping is RelationalTypeMapping elementTypeMapping2
&& (elementTypeMapping1.StoreType != elementTypeMapping2.StoreType
|| (elementTypeMapping1.Converter?.ProviderClrType ?? elementTypeMapping1.ClrType)
!= (elementTypeMapping2.Converter?.ProviderClrType ?? elementTypeMapping2.ClrType)))
Comment on lines +2406 to +2408

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a case of #10434. We should not attempt to fix this here.

{
throw new InvalidOperationException(
RelationalStrings.SetOperationOverCollectionsWithIncompatibleElementMappings(
elementTypeMapping1.StoreType, elementTypeMapping2.StoreType));
}

var projectionAlias = GenerateUniqueColumnAlias(
GetProjectionAlias(projectionMember)
?? (innerColumn1 as ColumnExpression)?.Name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,11 @@ protected override string GetJsonElementColumnName(TableExpressionBase tableExpr
&& (
translatedItem is ColumnExpression { IsNullable: false } or SqlConstantExpression { Value: not null }
|| !translatedItem.Type.IsNullableType()
|| (json.Type.GetSequenceType() is var elementClrType && !elementClrType.IsNullableType())))
|| (json.Type.GetSequenceType() is var elementClrType && !elementClrType.IsNullableType()))
// JSON_CONTAINS() compares the item with the elements as they're stored in the JSON, so the item must be sent in the same
// representation. If the elements have a value converter that changes it (e.g. int converted to string), the item would
// have to be converted too; use the OPENJSON translation instead, which applies the element mapping to the item.
&& IsStoredLikeItem(json.TypeMapping!.ElementTypeMapping as RelationalTypeMapping, translatedItem))
{
// JSON_CONTAINS returns 1 if found, 0 if not found. It's a search condition expression.
var jsonContains = _sqlExpressionFactory.Equal(
Expand All @@ -749,6 +753,22 @@ protected override string GetJsonElementColumnName(TableExpressionBase tableExpr
return base.TranslateContains(source, item);
}

private bool IsStoredLikeItem(RelationalTypeMapping? elementTypeMapping, SqlExpression item)
{
if (elementTypeMapping is null)
{
return true;
}

var itemTypeMapping = item.TypeMapping ?? _typeMappingSource.FindMapping(item.Type);

return itemTypeMapping is null
|| GetStoredClrType(elementTypeMapping) == GetStoredClrType(itemTypeMapping);

static Type GetStoredClrType(RelationalTypeMapping typeMapping)
=> (typeMapping.Converter?.ProviderClrType ?? typeMapping.ClrType).UnwrapNullableType();
}

/// <summary>
/// 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,15 @@ when QueryableMethods.IsSumWithSelector(method):
navigationTreeExpression);
}

if (IsProjectedPrimitiveCollection(firstArgument, out var projectedElementType))
{
// The collection was projected out of a subquery (e.g. by a set operation), which loses the
// PrimitiveCollectionReference that would otherwise keep the collection queryable, so preserve the AsQueryable (#33258).
return Expression.Call(
QueryableMethods.AsQueryable.MakeGenericMethod(projectedElementType),
firstArgument);
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved
}

return UnwrapCollectionMaterialization(firstArgument);
}

Expand Down Expand Up @@ -1561,6 +1570,27 @@ private NavigationExpansionExpression ProcessSelectMany(
throw new InvalidOperationException(CoreStrings.TranslationFailed(collectionSelector.Print()));
}

// An array or IList of non-entity elements that is either the element of a projection, or a member of an element that was
// projected into an anonymous type. Entity collections are excluded; they're navigations, not primitive collections.
private bool IsProjectedPrimitiveCollection(Expression expression, out Type elementType)
{
elementType = null!;

if (expression is not (NavigationTreeExpression { Value.NodeType: ExpressionType.Default }
or MemberExpression { Expression: NavigationTreeExpression { Value.NodeType: ExpressionType.New or ExpressionType.Default } })
|| expression.Type == typeof(byte[])
|| expression.Type.TryGetElementType(typeof(IQueryable<>)) != null
|| expression.Type.TryGetElementType(typeof(IEnumerable<>)) is not { } candidate
|| !(expression.Type.IsArray || typeof(IList<>).MakeGenericType(candidate).IsAssignableFrom(expression.Type))
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved
|| _queryCompilationContext.Model.FindEntityType(candidate) != null)
{
return false;
}

elementType = candidate;
return true;
}

private NavigationExpansionExpression ProcessSetOperation(
NavigationExpansionExpression outerSource,
MethodInfo genericMethod,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1822,6 +1822,86 @@ WHERE ARRAY_CONTAINS(@ints, c["Int"])
""");
}

public override async Task Concat_of_column_collections_then_Contains()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_column_collections_then_Contains);

AssertSql();
}

public override async Task Union_of_column_collections_then_Contains()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Union_of_column_collections_then_Contains);

AssertSql();
}

public override async Task Concat_of_anonymous_types_with_column_collection_then_Contains()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_anonymous_types_with_column_collection_then_Contains);

AssertSql();
}

public override async Task Concat_of_column_collections_then_Where_Count()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_column_collections_then_Where_Count);

AssertSql();
}

public override async Task Concat_of_string_column_collections_then_Contains()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_string_column_collections_then_Contains);

AssertSql();
}

public override async Task Concat_of_column_collections_then_Contains_parameter()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_column_collections_then_Contains_parameter);

AssertSql();
}

public override async Task Concat_of_column_collections_then_Contains_then_Select_Count()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_column_collections_then_Contains_then_Select_Count);

AssertSql();
}

public override async Task Distinct_of_column_collection_then_Contains()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Distinct_of_column_collection_then_Contains);

AssertSql();
}

public override async Task Concat_of_column_collections_then_Select_Contains_with_client_argument()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_column_collections_then_Select_Contains_with_client_argument);

AssertSql();
}

public override async Task Concat_of_List_column_collections_then_Contains()
{
// Set operations and DISTINCT over whole documents aren't supported
await AssertTranslationFailed(base.Concat_of_List_column_collections_then_Contains);

AssertSql();
}

public override async Task Column_collection_Distinct()
{
// TODO: Subquery pushdown, #33968
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1544,6 +1544,22 @@ public virtual Task Project_primitive_collection_mapped_to_column()
Assert.Equal(2, tags.Count);
Assert.Equal(new[] { "a", "b" }, tags[0]);
Assert.Null(tags[1]);
""");

// #33258: Contains (with a captured value) and Count over a primitive collection column that was projected out of a set operation.
// This makes sure the AsQueryable fallback for such a collection is intercepted, compiled and executed under precompilation.
[Fact]
public virtual Task Set_operation_over_primitive_collection_column_then_Contains_and_Count()
=> Test(
"""
var value = "a";
var tags = await context.EntitiesWithPrimitiveCollection.Where(e => e.Id == 1).Select(e => e.Tags!)
.Concat(context.EntitiesWithPrimitiveCollection.Where(e => e.Id == 1).Select(e => e.Tags!))
.Where(t => ((IEnumerable<string>)t).Contains(value) && ((IEnumerable<string>)t).Count(x => x != "b") == 1)
.ToListAsync();

Assert.Equal(2, tags.Count);
Assert.All(tags, t => Assert.Equal(new[] { "a", "b" }, t));
""");

public class PrecompiledQueryContext(DbContextOptions options) : DbContext(options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,67 @@ protected abstract DbContextOptionsBuilder SetParameterizedCollectionMode(
DbContextOptionsBuilder optionsBuilder,
ParameterTranslationMode parameterizedCollectionMode);

[Fact] // #33258
public virtual async Task Concat_of_column_collections_with_same_element_conversion_then_Contains()
{
var contextFactory = await InitializeNonSharedTest<TestContext>(
onModelCreating: mb => mb.Entity<TestEntityWithConvertedInts>(b =>
{
b.Property(e => e.Id).ValueGeneratedNever();
b.PrimitiveCollection(e => e.Ints).ElementType().HasConversion<string>();
}),
seed: context =>
{
context.AddRange(
new TestEntityWithConvertedInts { Id = 1, Ints = [1, 10] },
new TestEntityWithConvertedInts { Id = 2, Ints = [2, 20] });
return context.SaveChangesAsync();
});

await using var context = contextFactory.CreateDbContext();

var results = await context.Set<TestEntityWithConvertedInts>().Select(e => e.Ints)
.Concat(context.Set<TestEntityWithConvertedInts>().Select(e => e.Ints))
.Where(x => x.Contains(10))
.ToListAsync();

Assert.Equal(2, results.Count);
Assert.All(results, r => Assert.Equal([1, 10], r));
}

[Fact] // #33258
public virtual async Task Concat_of_column_collections_with_different_element_conversions_throws()
{
var contextFactory = await InitializeNonSharedTest<TestContext>(
onModelCreating: mb =>
{
mb.Entity<TestEntity>().Property(e => e.Id).ValueGeneratedNever();
mb.Entity<TestEntityWithConvertedInts>(b =>
{
b.Property(e => e.Id).ValueGeneratedNever();
b.PrimitiveCollection(e => e.Ints).ElementType().HasConversion<string>();
});
},
seed: context =>
{
context.AddRange(
new TestEntity { Id = 1, Ints = [1] },
new TestEntityWithConvertedInts { Id = 1, Ints = [1] });
return context.SaveChangesAsync();
});

await using var context = contextFactory.CreateDbContext();

// The two collections are stored differently ([1] and ["1"]), so the set operation result has no single element mapping.
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => context.Set<TestEntity>().Select(e => e.Ints!)
.Concat(context.Set<TestEntityWithConvertedInts>().Select(e => e.Ints))
.Where(x => x.Contains(1))
.ToListAsync());

Assert.Contains("aren't compatible", exception.Message);
}

[Theory, MemberData(nameof(IsAsyncData))]
public virtual Task Project_collection_with_identity_select_split_query(bool async)
=> AssertQuery(
Expand Down
Loading
Loading