# Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 数据库操作预期影响 1 行，但实际影响了 0 行。自加载实体以来，数据可能已被修改或删除。

- **ID:** `dotnet/ef-core-savechanges-optimistic-concurrency`
- **领域:** dotnet
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

当另一个用户或进程在加载实体和调用 SaveChanges 之间修改或删除了同一行，并且并发令牌（如 RowVersion）不匹配时，会发生乐观并发冲突。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 6.0 | active | — | — |
| 7.0 | active | — | — |
| 8.0 | active | — | — |
| 9.0 | active | — | — |

## 解决方案

1. ```
   Implement a retry loop that catches DbUpdateConcurrencyException, refreshes the entity from the database using 'await context.Entry(entity).ReloadAsync()', and then reapplies changes before calling SaveChanges again.
   ```
2. ```
   Use a database-first approach with a timestamp column: add a byte[] property annotated with '[Timestamp]' to the entity, and ensure all updates include the original timestamp value in the WHERE clause.
   ```

## 无效尝试

- **** — Disabling concurrency tokens by removing RowVersion properties allows overwrites without conflict detection, but can lead to lost updates and data corruption in multi-user scenarios. (70% 失败率)
- **** — Retrying the entire transaction without refreshing the entity from the database will still use the stale concurrency token, causing the same error repeatedly. (80% 失败率)
