C
C#2mo ago
ZML

DbUpdateConcurrencyException

Hello, I have an issue with Entity Framework. In my application, I have created an endpoint for creating employee accounts, which creates an account using Identity, and also creates the Employee and EmployeeProfile models. When I call the endpoint, I get the following error: 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. Can anyone point me in the right direction as to where the problem might lie and what I should fix? I’m attaching screenshots of the code.
No description
No description
No description
No description
No description
5 Replies
Becquerel
Becquerel2mo ago
is your salonRepository just a DbContext? how is it being created/instantiated? this exception, as the name suggests, happens, when you're doing threading/async stuff incorrectly
ZML
ZML2mo ago
The salonRepository is a middle layer following the repository pattern, which abstracts the data access logic using DbContext. It's not just a DbContext but a class that encapsulates it. The repository is initialized in Dependency Injection (DI) using AddScoped.
No description
Omnissiah
Omnissiah2mo ago
there is not abstraction there not even SaveChanges the class is only copying some DbSet methods without adding anything
jcotton42
jcotton422mo ago
You should not use AddAsync, it is only used for very specific value generation scenarios. Also, do not use Update either, instead pull the entity and modify its props. And like Mutable said, there's no point to that repo at all.
ZML
ZML2mo ago
As for the repository, I would like to implement repository patterns to separate database access logic. In the services/controllers, I want to work through the repository. I read a bit about AddAsync and Update, and indeed, in my case, they are unnecessary, but this still doesn't solve my problem. After adding a new employee to the employees collection on the Salon instance, even if I don't use Update, when calling Save on the DbContext, I still get the same error.
Want results from more Discord servers?
Add your server