You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Adds experimental (EF9107) ExecuteMerge, ExecuteMergeAsync, ExecuteMergeReturning and ExecuteMergeReturningAsync bulk operators that
insert source rows into a target table and update rows that conflict on a
declared set of columns (an "upsert"), without going through the change
tracker or SaveChanges.
Core: MergeBuilder / MergeUpdateSettersBuilder / MergeInsertSettersBuilder
for Match / WhenMatched / WhenNotMatched, plus the TranslateExecuteMerge
hook and ExecuteMergeMatch.
Relational: MergeExpression / MergeColumnReferenceExpression nodes, plumbed
through QuerySqlGenerator (VisitMerge), SqlNullabilityProcessor and the
shaped-query compiler (including a RETURNING shaper). Base VisitMerge throws;
providers opt in.
SQLite: lowers to INSERT ... ON CONFLICT ... DO UPDATE/DO NOTHING with
optional RETURNING.
Functional tests are included for SQLite (DO NOTHING / DO UPDATE, explicit and
default inserts, RETURNING sync + async, source-key matching, computed-column
exclusion).
Introduces ExecuteMerge, ExecuteMergeAsync, ExecuteMergeReturning and
ExecuteMergeReturningAsync as experimental (EF9107) bulk operators that
insert source rows into a target table and update rows that conflict on a
declared set of columns (an "upsert"), without going through the change
tracker or SaveChanges.
Core:
- MergeBuilder / MergeUpdateSettersBuilder / MergeInsertSettersBuilder for
configuring Match, WhenMatched and WhenNotMatched clauses.
- TranslateExecuteMerge hook and ExecuteMergeMatch on
QueryableMethodTranslatingExpressionVisitor.
Relational:
- MergeExpression / MergeColumnReferenceExpression SQL nodes, plumbed
through QuerySqlGenerator (VisitMerge), SqlNullabilityProcessor and the
shaped-query compiler (including a RETURNING shaper).
- Base VisitMerge throws; providers opt in by overriding it.
SQLite:
- VisitMerge lowers to INSERT ... ON CONFLICT ... DO UPDATE/DO NOTHING,
with optional RETURNING.
Behavior:
- Match honors the source-side key selector, so matching on a differently
named source member produces the correct conflict/insert values.
- The default (no WhenNotMatched) insert excludes computed columns.
Part of dotnet#4526
An empty WhenNotMatched callback leaves insertProperties empty. For a non-empty source, constructing RowValueExpression(values) then fails because row values must be non-empty; for an empty source the SQLite generator would also produce an invalid empty column list. This clause needs the same explicit empty-setter validation or a defined default-values insert semantics.
…xecuteMerge
ExecuteMerge previously didn't check for the mapping strategies and table-sharing
scenarios that ExecuteDelete/ExecuteUpdate already reject, so unsupported cases
would fail confusingly or produce incorrect SQL instead of a clear error.
…n async entry points
Mirrors the DynamicDependency annotation already on ExecuteUpdateAsync, since
ExecuteMergeAsync and ExecuteMergeReturningAsync build expression trees against
private overloads only reachable via reflection.
MergeExpression didn't implement IRelationalQuotableExpression like
DeleteExpression/UpdateExpression do, so precompiling a query with
ExecuteMerge failed with a generic "unsupported constant type" error
instead of a clear diagnostic.
… target entity
The default insert path read source-row values with the target entity's
property getter, which casts its argument to the target CLR type; this threw
InvalidCastException whenever TSource wasn't TTarget (e.g. a DTO). Build the
accessor against the actual source type's same-named member instead.
Also fix QueryRootProcessor, which didn't honor the source parameter's
[NotParameterized] attribute and rewrote it into a query root whenever the
source type wasn't a model entity, breaking ExecuteMerge's translation before
it even started for any non-entity source type.
A valid returning selector can contain no target property, such as t => 1 or t => new { Value = 1 }. In that case projections remains empty, but the SQLite generator still appends RETURNING with no expression, yielding invalid SQL. Either translate constant-only projections or reject them during translation.
Source member mappings incorrectly resolve against target entity
The value translator resolves every member by its name on the target entity, even when the member is rooted at the source parameter. This rejects SetProperty(t => t.Name, (t, s) => s.Code) when Code is a DTO-only member, and can bind to the wrong target column when both types contain similarly named members. Source-member references need to be mapped to the inserted target column (or explicitly diagnosed as unsupported).
Empty matched setters generate invalid DO UPDATE SQL
WhenMatched(_ => { }) produces a non-null but empty setter list. This branch then emits DO UPDATE SET with no assignments, which is invalid SQLite syntax instead of behaving as a no-op (or producing a clear validation error). Treat an empty list consistently with the omitted clause or validate it before SQL generation.
A valid selector such as t => 1 has no target member, so BuildReturning produces an empty Returning list while this condition still emits RETURNING . SQLite rejects that statement (incomplete input), and the public method cannot return the requested constant projection. Either reject projections with no SQL projection during translation or add a valid projection/shaper for them.
…xecuteMerge inserts
Address two PR review comments: the target-shape check only rejected a
Predicate, silently ignoring Take/Skip/OrderBy/Distinct/GroupBy/Having even
though the generated MERGE always targets the whole table; and explicit
WhenNotMatched setters that omitted a match/conflict column caused that
column to be left out of the INSERT entirely, so the new row could never
actually be matched by a later merge.
Reject matching the same column more than once, which generated invalid
ON CONFLICT SQL. Name ExecuteMergeReturning in the not-supported errors when
it's the API being called, and make the unsupported-expression error
clause-agnostic since it's also thrown for insert values.
Translate a source member referenced in WhenMatched to the "excluded" column
it was inserted into unchanged, rather than resolving it by name against the
target entity; this makes DTO-only members work and throws a clear error when
the member isn't inserted as-is. Reject returning selectors that read no
target column, which produced an empty RETURNING clause.
Also mark inlined source values as sensitive so they're redacted from logs
unless sensitive data logging is enabled, and add the missing
ExecuteMergeNotSupportedInPrecompiledQueries API baseline entry.
When WhenMatched is configured with an empty setter callback, UpdateSetters is a non-null empty list, so this branch emits DO UPDATE SET with no assignments. SQLite rejects that SQL at execution time; either treat an empty clause as DO NOTHING or reject it during translation with a clear error.
The insert only populates the entity type's own properties, so complex
property columns were silently left out of not-matched inserts. Owned types
don't need a check: their auto-included navigations already fail the single
entity type check.
Also add tests covering the owned-type rejection and an empty WhenMatched,
which already translates to DO NOTHING.
Disabling auto-inclusion with Navigation(o => o.ShipTo).AutoInclude(false) lets an owner pass the shaper check, and the table-sharing check excludes owned types. An insert can then silently omit the supplied optional owned reference's values. Reject ownership navigations explicitly and add a shared regression with auto-inclusion disabled.
Alias merge target to avoid excluded table name collision
When the target table is named excluded, SQLite resolves excluded."Name" in DO UPDATE to the existing row, so a source-based update retains the old value while reporting an affected row. Emit the target's generated alias to avoid this name collision, and add a regression for an excluded table.
- Read entity-typed source rows through model metadata, so non-public properties work
- Alias the SQLite target when the table is named "excluded"
- Reject nullable-to-non-nullable casts in match, insert and update selectors
- Reject inserted source members whose type doesn't match the target property
- Assert SQL baselines for all SQLite ExecuteMerge tests and add Check_all_tests_overridden
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved merge-validation gaps permit incompatible type assignments, retain captured instances in cached RETURNING shapers, and allow owned shared-table mappings that omit owned data when auto-includes are disabled.
…atched types
- Reject non-mappable constants (e.g. 'this') in ExecuteMergeReturning selectors, as regular projections do
- Reject WhenMatched source and target member references whose CLR type doesn't match the property
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Parameterized merge setters can write incompatible values without runtime type validation, and nullable merge expressions violate SQL expression invariants, causing failures in Debug builds.
…ession types
- Reject setter value parameters (e.g. from SetProperty<object>) whose runtime type doesn't match the property
- Unwrap nullable value types in MergeColumnReferenceExpression and MergeSourceMemberExpression
- Take source row parameter nullability from the source member's type
- Update the API baseline for the new exception messages
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed to weigh unpublished correctness risks, especially a critical match-key arity mismatch that can silently alter matching behavior or cause runtime failures.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds experimental (EF9107)
ExecuteMerge,ExecuteMergeAsync,ExecuteMergeReturningandExecuteMergeReturningAsyncbulk operators thatinsert source rows into a target table and update rows that conflict on a
declared set of columns (an "upsert"), without going through the change
tracker or
SaveChanges.MergeBuilder/MergeUpdateSettersBuilder/MergeInsertSettersBuilderfor
Match/WhenMatched/WhenNotMatched, plus theTranslateExecuteMergehook and
ExecuteMergeMatch.MergeExpression/MergeColumnReferenceExpressionnodes, plumbedthrough
QuerySqlGenerator(VisitMerge),SqlNullabilityProcessorand theshaped-query compiler (including a RETURNING shaper). Base
VisitMergethrows;providers opt in.
INSERT ... ON CONFLICT ... DO UPDATE/DO NOTHINGwithoptional
RETURNING.Functional tests are included for SQLite (DO NOTHING / DO UPDATE, explicit and
default inserts, RETURNING sync + async, source-key matching, computed-column
exclusion).
Part of #4526