dotnet / dotnet/EntityFramework.Docs

Resolving concurrency conflicts in a batch-process misleading guidance

Open
#4,416 0 comments 0 reactions 0 assignees View on GitHub
area-save-changes
Dominant language
Mermaid
Stars
1.7k
Forks
2k
Avg merge
7d 23h
Merged PRs (30d)
16

Description

in [Resolving concurrency conflicts](https://learn.microsoft.com/en-us/ef/core/saving/concurrency?tabs=data-annotations#resolving-concurrency-conflicts):

> Or if your application is performing an automated update, it can simply loop and retry immediately, after re-querying the data.
> ...
> 2. Use DbUpdateConcurrencyException.Entries to prepare a new set of changes for the affected entities.

The example resolution suggests the following code:

```cs
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
```

This suggests that there could be multiple entries with a conflict. This would be great when doing batch updates on large batches. But once in production you'll eventual run into this issue from 9 years ago:

https://github.com/dotnet/efcore/issues/1002#issuecomment-67401333:
> Currently we only return the first one.

Translation: the suggested conflict resolution will retry the save operation for _every_ conflict! Instead of efficiently querying all conflicting entries, the code will:

1. try to save
2. fail with DbUpdateConcurrencyException
3. load a single entry from the database
4. go to 1.

With sufficient batch sizes, this will be very inefficient!

---
#### Document Details

⚠ *Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.*

* ID: 649fbab8-b960-6873-14bf-188d14757fee
* Version Independent ID: f5ee3135-54c8-689c-e28b-b203b376bd6f
* Content: [Handling Concurrency Conflicts - EF Core](https://learn.microsoft.com/en-us/ef/core/saving/concurrency?tabs=data-annotations)
* Content Source: [entity-framework/core/saving/concurrency.md](https://github.com/dotnet/EntityFramework.Docs/blob/main/entity-framework/core/saving/concurrency.md)
* Product: **entity-framework**
* Technology: **entity-framework-core**
* GitHub Login: @ajcvickers
* Microsoft Alias: **avickers**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.