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
14 changes: 7 additions & 7 deletions docs/failing-spec-tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ Regenerate every figure below (and the `Count` column in the tables) with

| | Before the spec port (`main` @ `cc5151f9`) | Now (rebuilt on `release`) |
| --- | --- | --- |
| `// Fails:` tag lines | 1,206 | 4,995 |
| Distinct tagged test methods, any EF version | 1,175 | 3,514 |
| `// Fails:` tag lines | 1,206 | 4,987 |
| Distinct tagged test methods, any EF version | 1,175 | 3,508 |
| ... active in the EF8 build | 1,064 | 2,626 |
| ... active in the EF9 build | 1,141 | 3,149 |
| ... active in the EF10 build | 882 | 3,292 |
| ... active in the EF11 build | not measured | 3,322 |
| ... active in the EF9 build | 1,141 | 3,143 |
| ... active in the EF10 build | 882 | 3,288 |
| ... active in the EF11 build | not measured | 3,318 |
| Test bases still ignored by `MongoComplianceTest` (distinct entries) | 142 | 58 |

Full `SpecificationTests` run (Docker, `MONGODB_URI`/`ATLAS_URI` unset, one EF version at a time): EF8 18,159 passed / 73 skipped,
Expand Down Expand Up @@ -192,7 +192,7 @@ These entries appear in `// Fails:` comments without an `EF-` or `CSHARP-` refer
| EF-X021 | Filtered Include / query filter on cross-collection target not translated | 0 |
| EF-X022 | Join/GroupJoin whose inner source is a filtered or ordered sub-query is rejected | 14 |
| EF-X024 | `Where`/entity materialization over a flattened multi-join chain onto ambiguous same-navigation or navigation-less siblings is not translated | 2 |
| EF-X016 | Bulk `ExecuteUpdate`/`ExecuteDelete` source restricted to a single collection scoped by `Where` | 61 |
| EF-X016 | Bulk `ExecuteUpdate`/`ExecuteDelete` source restricted to a single collection scoped by `Where` | 55 |
| EF-X400 | **Fixed:** `DbUpdateConcurrencyException` is now raised through `ISaveChangesInterceptor.ThrowingConcurrencyException[Async]` (#104); a suppressed conflict is counted as applied, like the relational providers | 0 |
| EF-X401 | Ambiguous foreign key discovery between a join/owned type and its owner (`Both relationships ... could use {'PostId'}`) | 4 |
| EF-X402 | Projecting an owned collection navigation directly (`Select(e => e.OwnedCollection)`) is not translated | 1 |
Expand Down Expand Up @@ -479,7 +479,7 @@ Affected: 1 test (`NorthwindMiscellaneousQueryMongoTest.Where_nanosecond_and_mic
### EF-X016 — Bulk `ExecuteUpdate`/`ExecuteDelete` source restricted to a single collection scoped by `Where`
Comment pattern: `// Fails: ExecuteUpdate/ExecuteDelete source restricted to a Where predicate; <shape> unsupported EF-X016`.
Test-body pattern: `AssertTranslationFailed(() => base.X(...))`.
Affected: 61 tests: 42 in `NorthwindBulkUpdatesMongoTest.cs`, 11 in `NonSharedModelBulkUpdatesMongoTest.cs`, 4 in `InheritanceBulkUpdatesMongoTest.cs` and 4 in `FiltersInheritanceBulkUpdatesMongoTest.cs`. By design, the provider supports bulk `ExecuteUpdate`/`ExecuteDelete` only against a single collection scoped by `Where`, with constant / parameter / self-referencing scalar setters (see README "What is supported" and EF-107). The EF conformance suite exercises shapes outside that subset — joins / correlated subqueries, set operations (`Except`/`Intersect`), `GroupBy`, `SelectMany`, cross-document navigation predicates, non-entity projection sources, and multiple-collection updates — and the provider rejects them during translation with an `InvalidOperationException` whose message reports the LINQ expression could not be translated. This is a documented limitation rather than a bug to fix; the ticket tracks the boundary so any future expansion of the supported subset (or a behavior change) is detected. Most shapes are rejected by compile-time bulk-source validation; a few (e.g. a `GroupBy` subquery inside the `Where` predicate) only fail when the filter is built at execution time, where a translation guard (`TranslateBulkOrThrow` in `MongoShapedQueryCompilingExpressionVisitor`) converts the raw driver/expression exception into the same canonical non-query translation failure. A handful of sibling shapes surface differently and are tagged separately: cross-DbSet `GroupBy` rejections under [EF-216](https://jira.mongodb.org/browse/EF-216), and the `$unionWith`-in-transaction `Concat`/`Union` cases under `EF-X002`.
Affected: 55 tests: 42 in `NorthwindBulkUpdatesMongoTest.cs`, 5 in `NonSharedModelBulkUpdatesMongoTest.cs`, 4 in `InheritanceBulkUpdatesMongoTest.cs` and 4 in `FiltersInheritanceBulkUpdatesMongoTest.cs`. By design, the provider supports bulk `ExecuteUpdate`/`ExecuteDelete` only against a single collection scoped by `Where`, with constant / parameter / self-referencing scalar setters (see README "What is supported" and EF-107). The EF conformance suite exercises shapes outside that subset — joins / correlated subqueries, set operations (`Except`/`Intersect`), `GroupBy`, `SelectMany`, cross-document navigation predicates, non-entity projection sources, and multiple-collection updates — and the provider rejects them during translation with an `InvalidOperationException` whose message reports the LINQ expression could not be translated. An entity type with an included navigation (an owned navigation is auto-included) is no longer part of that boundary: the outermost auto-include `Select(Include)` wrapper is stripped (#69), so the formerly tagged `Delete_entity_with_auto_include`, `Delete_aggregate_root_when_eager_loaded_owned_collection`, `Delete_aggregate_root_when_table_sharing_with_owned`, `Delete_with_owned_collection_and_non_natively_translatable_query` and (EF9) `Update_non_owned_property_on_entity_with_owned`/`2` now pass. This is a documented limitation rather than a bug to fix; the ticket tracks the boundary so any future expansion of the supported subset (or a behavior change) is detected. Most shapes are rejected by compile-time bulk-source validation; a few (e.g. a `GroupBy` subquery inside the `Where` predicate) only fail when the filter is built at execution time, where a translation guard (`TranslateBulkOrThrow` in `MongoShapedQueryCompilingExpressionVisitor`) converts the raw driver/expression exception into the same canonical non-query translation failure. A handful of sibling shapes surface differently and are tagged separately: cross-DbSet `GroupBy` rejections under [EF-216](https://jira.mongodb.org/browse/EF-216), and the `$unionWith`-in-transaction `Concat`/`Union` cases under `EF-X002`.

**Remaining unsupported shapes — grouped by root cause.** The unifying cause: bulk execution needs a source the provider can express as a single-collection filter (single command) or read to collect the target `_id`s (two-phase, selected by `Skip`/`Take` or `OfType<TDerived>()`). Every group below fails because the source shape itself cannot be translated — so neither phase 1 nor a single-command filter can be built. (Delete has the analogous cases; the `Update_*` methods are enumerated here since they are the larger set.)

Expand Down
9 changes: 9 additions & 0 deletions src/MongoDB.EntityFrameworkCore/Query/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ Gate and fallback:
EF10+ the C# compiler evaluates it inside the caller's `Action<UpdateSettersBuilder>`, so no call ever reaches the provider, and EF9
must agree. Refusal messages
print expressions through `ExpressionShapePrinter` (constants as `?`), never `Expression.ToString()`.
The source chain is always read through `MongoNonQueryExpression.UnwrapBulkOperator` (classifier, filter, two-phase id query,
null-element scan), which also strips the OUTERMOST auto-include wrapper navigation expansion leaves for an entity type with an
included navigation (always on EF9, and for `ExecuteDelete` on EF10+; #69). It loads related data only, so it never changes the
affected set. Two shapes, matched narrowly: `Select(e => Include(e, ...))` for an owned navigation (auto-included by convention),
and `LeftJoin(source, DbSet<Related>, ...)` + `Select(ti => Include(ti.Outer, nav, ti.Inner))` (n nested of each) for REFERENCE
navigations to another collection, which is stripped to `source`. A required navigation's inner `Join` is NOT stripped (it drops
documents whose reference dangles, changing the affected set), nor is a collection include, nor a `Where` above the join (a
predicate on the navigation, which stays unsupported); any other `Select` is still refused. A new reader of the chain must go
through `UnwrapBulkOperator`, not through `CapturedExpression` directly.
- **A recognizer turning a correlated `DbSet` subquery into a navigation** (`db.Orders.Where(o => o.CustomerId == c.X)`
-> `c.Orders`) must prove `c.X` is that navigation's FK principal key via `NativeCorrelationMatcher` (single-property FK;
alternate key via `ForeignKey.PrincipalKey`; composite declines). Binding emits `$lookup {localField: principalKey}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,136 @@ public MongoNonQueryExpression(
/// <see cref="MongoQueryExpression.CapturedExpression"/>; walkers that scope the operation need only the source.
/// Only the four bulk operators are unwrapped: other methods on that type (AsNoTracking, IgnoreQueryFilters, TagWith, ...) stay in
/// the chain so the classifier can see and reject them rather than having them silently discarded.
/// <para>
/// An outermost auto-include wrapper is unwrapped too (<see cref="StripIncludeWrapper"/>), so every consumer of the source chain
/// (classification, filter, two-phase id query, null-element scan) sees the same chain.
/// </para>
/// </summary>
public static Expression? UnwrapBulkOperator(Expression? capturedExpression)
=> capturedExpression is MethodCallExpression { Method: { DeclaringType: var declaringType, Name: var name } } call
&& declaringType == typeof(EntityFrameworkQueryableExtensions)
&& Array.IndexOf(BulkOperatorNames, name) >= 0
? call.Arguments[0]
: capturedExpression;
=> StripIncludeWrapper(
capturedExpression is MethodCallExpression { Method: { DeclaringType: var declaringType, Name: var name } } call
&& declaringType == typeof(EntityFrameworkQueryableExtensions)
&& Array.IndexOf(BulkOperatorNames, name) >= 0
? call.Arguments[0]
: capturedExpression);

/// <summary>
/// Removes the auto-include wrapper that navigation expansion leaves as the OUTERMOST operator when the entity type has an included
/// navigation: always for ExecuteDelete, and for ExecuteUpdate on EF9 (#69). It only loads related data into the result, so it does
/// not change which documents match, and a bulk operation returns none of it. Two shapes, matched narrowly (anything else stays in the
/// chain for the classifier to reject):
/// <list type="bullet">
/// <item>
/// <c>Select(e => Include(e, ...))</c>, an embedded (owned) navigation: a <c>Select</c> whose lambda body is nothing but
/// <see cref="IncludeExpression"/>s over the lambda's own parameter.
/// </item>
/// <item>
/// <c>LeftJoin(source, DbSet&lt;Related&gt;, ...).Select(ti => Include(ti.Outer, nav, ti.Inner))</c>, a REFERENCE navigation to another
/// collection: a left-outer join (so a document whose reference is missing is still in the set, and one match at most, since it is
/// a reference) that only feeds the include. Stripping both leaves <c>source</c>. An inner <c>Join</c>, which a required navigation may
/// produce, is NOT accepted: it can drop documents whose reference dangles, which would change the affected set.
/// </item>
/// </list>
/// Several included reference navigations arrive as ONE <c>Select</c> of nested includes over nested <c>LeftJoin</c>s, handled the same
/// way. Repeated while the chain still starts with one wrapper.
/// </summary>
private static Expression? StripIncludeWrapper(Expression? expression)
{
while (TryStripIncludeWrapper(expression, out var source))
{
expression = source;
}

return expression;
}

private static bool TryStripIncludeWrapper(Expression? expression, out Expression? source)
{
source = null;
if (expression is not MethodCallExpression { Method: { IsGenericMethod: true } method, Arguments: [var select, var selector] }
|| method.GetGenericMethodDefinition() != QueryableMethods.Select
|| selector.UnwrapLambdaFromQuote() is not { Parameters: [var parameter], Body: IncludeExpression outermost })
{
return false;
}

// The nested includes, outermost first, down to the entity they all include onto.
var includes = new List<IncludeExpression>();
Expression entity = outermost;
while (entity is IncludeExpression nested)
{
includes.Add(nested);
entity = nested.EntityExpression;
}

if (entity == parameter)
{
source = select;
return true;
}

// n included reference navigations: the entity is p.Outer (n times) and include j reads p.Outer (j times).Inner, over n nested
// LeftJoins that only feed those includes.
var count = includes.Count;
if (!parameter.Type.IsTransparentIdentifierType() || !IsOuterPath(entity, parameter, count))
{
return false;
}

for (var j = 0; j < count; j++)
{
if (includes[j].Navigation.IsCollection
|| includes[j].NavigationExpression is not MemberExpression { Member.Name: "Inner", Expression: { } owner }
|| !IsOuterPath(owner, parameter, j))
{
return false;
}
}

var current = select;
for (var j = 0; j < count; j++)
{
if (current is not MethodCallExpression
{
Method: { Name: "LeftJoin", IsGenericMethod: true } join,
Arguments: [var joinSource, QueryRootExpression, _, _, var resultSelector]
}
|| !(join.DeclaringType == typeof(Queryable) || join.DeclaringType?.Assembly == typeof(DbContext).Assembly)
|| !IsTransparentIdentifierOfParameters(resultSelector.UnwrapLambdaFromQuote()))
{
return false;
}

current = joinSource;
}

source = current;
return true;
}

// parameter.Outer.Outer... (count times); count 0 is the parameter itself.
private static bool IsOuterPath(Expression expression, ParameterExpression parameter, int count)
{
while (count > 0)
{
if (expression is not MemberExpression { Member.Name: "Outer" } member || !member.IsTransparentIdentifierOuterOrInnerAccess())
{
return false;
}

expression = member.Expression!;
count--;
}

return expression == parameter;
}

// (o, i) => new TransparentIdentifier<TOuter, TInner>(o, i): the plain pairing EF writes for a join feeding an include.
private static bool IsTransparentIdentifierOfParameters(LambdaExpression selector)
=> selector is { Parameters: [var outer, var inner], Body: NewExpression { Arguments: [var first, var second] } body }
&& body.Type.IsTransparentIdentifierType()
&& first == outer
&& second == inner;

// The canonical single-key / parameterless overloads. Matched by method definition, not by name (Query/AGENTS.md: reference-equality on
// MethodInfo), so overloads with different semantics are not admitted: OrderBy(keySelector, IComparer<T>) and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -850,26 +850,15 @@ public void Same_clr_type_at_several_paths_bulk_filter_and_set_use_each_paths_na

using (var db = Context(collection, ConfigureShipper))
{
#if EF9
// EF9 wraps an entity with an owned navigation (Depot) in an auto-include Select that EF's own bulk validation
// rejects. Pre-existing for ANY owned navigation (measured with no complex type), not complex-specific.
var ex = Assert.Throws<InvalidOperationException>(() => db.Entities.Where(s => s.Shipping.City == "B1")
.ExecuteUpdate(u => u.SetProperty(s => s.Billing.City, "bulk").SetProperty(s => s.Previous.Code, 5)));
Assert.Contains("The 'Select' operator is not supported in a bulk delete or update", ex.Message);
Assert.Equal(before["b"], Raw(collection).Find(Builders<BsonDocument>.Filter.Eq("Name", "b")).Single());
#else
Assert.Equal(1, db.Entities.Where(s => s.Shipping.City == "B1")
.ExecuteUpdate(u => u.SetProperty(s => s.Billing.City, "bulk").SetProperty(s => s.Previous.Code, 5)));
#endif
}

#if !EF9
var after = Raw(collection).Find(FilterDefinition<BsonDocument>.Empty).ToList().ToDictionary(d => d["Name"].AsString);
Assert.Equal(before["a"], after["a"]);
before["b"]["bill"]["bc"] = "bulk";
before["b"]["Previous"]["Code"] = 5;
Assert.Equal(before["b"], after["b"]);
#endif
}
#endif

Expand Down
Loading
Loading