Add support for AddOrUpdate (Upsert via SaveChanges)
维护者通常 2 天内回复
还没有人认领这个 Issue。
评估
调研方向
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 内容生成。
描述
Related:
- https://github.com/dotnet/efcore/issues/4526
- https://github.com/dotnet/efcore/issues/29897
- https://github.com/dotnet/efcore/issues/16949
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 withUpdate. - 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
acceptAllChangesOnSuccessbehavior. After acceptance, successful entries becomeUnchanged; 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, andDeletedoperations 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 小时
- 30 天内合并 PR
- 182
环境准备
在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
dotnet/efcore 的其他 Issue
-
customer-reported
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 2 天内回复
-
GroupBy element `OrderBy(...).First()`/`MaxBy` over an owned type mapped to its own table fails to translate可能已有人在做 @cincuranet 今天认领。 未关闭area-groupby area-query
难度 4/5 3-5 天 新手友好度 25/100
dotnet/efcore#39833 · 已指派 1 人 ·
维护者通常 2 天内回复
-
SQLite: Polygon.Length translates to GLength, which returns 0可能已有人在做 @cincuranet 今天认领。 未关闭area-query area-sqlite
难度 3/5 1-2 天 新手友好度 45/100
dotnet/efcore#39826 · 已指派 1 人 ·
维护者通常 2 天内回复
-
Migration lock with LockReleaseBehavior.Transaction doesn't prevent concurrent migrations since per-migration transactions可能已有人在做 @AndriySvyryd 于 1 天前认领。 未关闭area-migrations
dotnet/efcore#39824 · 已指派 1 人 ·
维护者通常 2 天内回复
-
Querying a TPC base type with a JSON complex property throws可能已有人在做 @cincuranet 于 1 天前认领。 未关闭area-query
难度 4/5 3-5 天 新手友好度 22/100
dotnet/efcore#39814 · 已指派 1 人 ·
维护者通常 2 天内回复
相似的 Issue
-
难度 2/5 1-3 小时 新手友好度 77/100
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 68/100
SubtitleEdit/subtitleedit#17247 ·
维护者通常 1 天内回复
-
Restore test cleanup fails on Windows when restored files are read-only可能已有人在做 @JamBalaya56562 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 68/100
duplicati/duplicati#8046 · 1 条评论 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 70/100
维护者通常 1 天内回复
-
Bundles Documentation
难度 2/5 1-3 小时 新手友好度 78/100
pyrevitlabs/pyRevit#4285 ·
维护者通常 1 天内回复