dotnet / dotnet/aspnetcore

DbUpdateConcurrencyException when using AutoSaveChanges

Open
#57,856 2 comments 0 reactions 1 assignee Claimed by @halter73 View on GitHub
area-identity investigate
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I'm using AutoSaveChanges = false on a custom UserStore implementation. Unfortunately, when I call multiple methods of UserManager which internally call "UpdateUserAsync(user)" I get a DbUpdateConcurrencyException. I took me a lot of time to figure out when this happens exactly. Is it possible that the UpdateUserAsync implementation attaches the same UserEntity multiple times? If so, can this be fixed please?

### Expected Behavior

No DbUpdateConcurrencyException.

### Steps To Reproduce

var userEntity = dbContext.Users.First();

await userManager.UpdateAsync(userEntity);

await userManager.RemoveAuthenticationTokenAsync(user, "provider", "tokenname");

await dbContext.SaveChangesAsync(cancellationToken);

### Exceptions (if any)

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See https://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyExceptionAsync(RelationalDataReader reader, Int32 commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected, CancellationToken cancellationToken)

### .NET Version

8

### Anything else?

_No response_

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.