Add support for AddOrUpdate (Upsert via SaveChanges)

オープン
#39,800 コメント 0 件 リアクション 1 件 担当者 0 名 GitHub で見る

メンテナーはふだん 2 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
8/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
活発
技術スタック
csharp, sql
領域
backend, databases

調査の方向性

This is a design-level proposal: a new EntityState.AddedOrModified, DbContext/DbSet AddOrUpdate methods, and provider-specific upsert strategies touching change tracking and SaveChanges. Start by reading the existing Add/Update handling in the change tracker and the modification-command preparation the issue mentions, then settle the design questions in the thread. Done would be an agreed design and a checklist item completed, not a patch from this issue alone.

索引モデルが issue の本文から書いたものです。

説明

area-save-changes

Related:

Goal: mark tracked entities for insert-or-update, deferring existence checks, SQL selection, batching, and generated-value propagation to SaveChanges. Unlike ExecuteMerge/ExecuteInsert, this API expresses intent, not a required SQL statement kind.

API and tracking

context.Products.AddOrUpdate(product);
context.Products.AddOrUpdateRange(products);
await context.SaveChangesAsync();

Add matching DbContext and DbSet<TEntity> methods, following the existing Add/Update overload conventions. Marking performs no existence check; value generation follows existing Add behavior, including async variants where needed.

Propose EntityState.AddedOrModified to represent unresolved upsert intent explicitly; do not overload Modified, whose normal meaning remains update-only. A generated primary key that is unset or temporary instead uses ordinary Added behavior. A set key does not prove that the row exists.

Match by the complete primary key only in the initial version. Alternate-key matching is deferred: it can discover a different identity and complicate identity-map and relationship fixup.

For a newly attached entity, mark all updateable scalar properties as modified, as Update does; this is not a patch inferred by comparing CLR defaults. Allow callers to refine the update mask through IsModified. Build the insert values separately using before-save behavior, defaults, and value-generation rules. Never update keys or silently override generated-column restrictions.

Reuse graph attachment, relationship fixup, and generated-key propagation, substituting upsert intent where Update would attach a set-key entity as modified. Do not reconcile collections, infer deletions, or create a second tracked instance for an existing key.

Automatic translation

Choose a strategy per compatible command group, based on the provider/version, mapping, concurrency tokens, triggers, required generated values, and dependency ordering. Correctness is mandatory; among equivalent strategies, prefer fewer round trips and effective batching.

Candidate Selection rule
Ordinary INSERT The generated key is unset/temporary; no existing identity is being addressed.
Native INSERT-based upsert Prefer when it preserves PK matching, update masks, concurrency, and generated-value readback; for example PostgreSQL/SQLite ON CONFLICT.
Native MERGE Use when it is a better supported fit; for example SQL Server, with provider-appropriate locking.
Transactional existence check plus UPDATE/INSERT Provider-defined fallback, with locking/isolation that protects the existence decision and handles concurrent insertions correctly. Never an unprotected SELECT-then-write.

These are candidates, not an unconditional syntax ranking. MySQL's any-unique-key conflict handling, for example, is ineligible if it could update a row other than the one identified by the PK. A provider must reject an unsupported configuration before executing its modifications rather than silently weaken semantics.

SaveChanges guarantees

  • Concurrency: honor original concurrency tokens on the update path, unlike the non-tracking operators. Determine existence by PK, then apply token predicates to the update. An existing row with a token mismatch causes DbUpdateConcurrencyException, never an attempted insert. A zero-row conditional update alone cannot distinguish absence from a concurrency conflict. Disconnected callers supply original tokens as with Update.
  • Values and relationships: propagate generated keys, computed values, and new concurrency tokens into the tracked instance on either path. Correlate results explicitly, not by native output order. Observe principal/dependent ordering; split batches when generated values are needed.
  • Unchanged matches: an update assigning identical values is still an update. If the update mask is empty, the match must not trigger a dummy update; validate any concurrency tokens and obtain required values through a correct provider readback strategy. Native MERGE output need not return skipped rows.
  • Transactions and acceptance: participate in normal SaveChanges transactions, savepoints, execution strategies, and acceptAllChangesOnSuccess behavior. After acceptance, successful entries become Unchanged; retain the pending intent when acceptance is deferred. Preserve retry safety, including ambiguous commit outcomes.
  • Counts and diagnostics: count saved state entries consistently with SaveChanges, not raw vendor affected-row totals. Existing explicit Added, Modified, and Deleted operations retain their meanings. Unsupported mappings or providers produce actionable errors.

Initial implementation checklist

  • Add APIs/state and integrate change detection, graph attachment, interceptors, diagnostics, acceptance, and failure handling.
  • Extend modification-command preparation with separate insert/update masks, original concurrency values, and generated-value requirements.
  • Add capability-based provider strategy selection, batching, safe fallback/readback, and relationship dependency handling.
  • Cover concurrent insertions, stale tokens, empty update masks, triggers, generated keys, unique-key conflicts, transactions, retries, and mixed ordinary/upsert saves.

Reuse SQL generation, parameterization, mapping validation, and output-correlation infrastructure from the companion designs; do not invoke the non-tracking public APIs from SaveChanges.

主要言語
C#
スター
14.8k
フォーク
3.5k
平均マージ
3日 7時間
マージ済み PR(30日)
182

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

dotnet/efcore のほかの issue

dotnet/efcore の issue をすべて見る

似ている issue

C# の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。