I keep getting this exception most of the time for the code below
But there is no concurrency in the system. No other process even runs on the database.
Is there anything fundamentally wrong with the code below?
I checked by printing the ChangeTracker as
exptContext.ChangeTracker.DebugView.LongView, and it appeared there was nothing wrong, but not sure
But there is no concurrency in the system. No other process even runs on the database.
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.
Is there anything fundamentally wrong with the code below?
- Delete existing records of the specified name by
- Fetching records of the relevant name, by using the Where clause
- Execute DbSet.RemoveRange
- Execute DbContext.SaveChanges
- Create a new record by
- Execute DbSet.Add
- Execute DbContext.SaveChanges
- Update the new record by
- Fetch the record again from the database by specifying its primary key
- Make modifications on the C# structure
- Execute DbSet.Update
- Execute DbContext.SaveChanges
C#:
[Test]
public void Expt2() {
string? userName = createUserViewRequest.userName;
var dbUserViews = exptContext.userViews.Where(
dbUserView => dbUserView.userName == userName);
if (dbUserViews.Count() > 0) {
exptContext.userViews.RemoveRange(dbUserViews);
exptContext.SaveChanges();
}
DbUserView initialView = createUserViewRequest.toDbUserView();
exptContext.userViews.Add(initialView);
exptContext.SaveChanges();
Thread.Sleep(2000);
DbUserView? _refreshView = exptContext.userViews.Find(
initialView.userName, initialView.fromUrl, initialView.startTime);
if (_refreshView == null)
Assert.Fail("Db fetch gave null view");
else {
DbUserView refreshView = (DbUserView)_refreshView;
refreshView.lastActiveTime = DateTime.Now.ToUniversalTime();
exptContext.userViews.Update(refreshView);
exptContext.SaveChanges();
}
}
I checked by printing the ChangeTracker as
exptContext.ChangeTracker.DebugView.LongView, and it appeared there was nothing wrong, but not sure
Last edited by a moderator: