4

New to MVC/EF... My MVC web app was created using the code first from database model since I already had the database (SQLExpress)...

I'm getting the following error when I try an update a record to the database:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded

I got this error when using the standard code generated using the code first from database Entity Framework model. Strange because I'm working on a standalone machine which no one else has accessing to.

Here is the code that was failing:

if (ModelState.IsValid)
{
    db.Entry(tblPropGroup).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}

So I wrote the following work around, which worked flawlessly for a while:

if (ModelState.IsValid)
{
db.Entry(_Prop).State = EntityState.Modified;
bool saveFailed;
do
{
 saveFailed = false;
 try
 {
 db.SaveChanges();
 }
 catch (DbUpdateConcurrencyException ex)
 {
 saveFailed = true;
 // Update original values from the database 
 var entry = ex.Entries.Single();
 entry.OriginalValues.SetValues(entry.GetDatabaseValues());
 }
} while (saveFailed); 

Can anyone explain why db.SaveChanges results in a DbUpdateConcurrencyException on a DB with no other users? It makes no difference if I make any changes to the data or not. I have 22 different tables I'm access in this program, about half won't work without this workaround.

DanielV
  • 2,076
  • 2
  • 40
  • 61
Steve
  • 79
  • 3
  • Could you show the complete method, I think this is related to the context, maybe it is still open and not closed after a previous operation. – DanielV Jul 25 '15 at 09:02
  • 1
    The only other line of code in that method is the return statement and the viewbag entries in the event that ModelState.IsValid returns false and none of the above code executes. – Steve Jul 26 '15 at 03:32

1 Answers1

0

I suspect this is related to a race condition related to the context of the database.

Here are some answers: side-effect of a feature called optimistic concurrency

Store update, insert, or delete statement affected an unexpected number of rows (0) EntityFramework

That may help.

It is better to use:

using(DBContext context = new DBContext())
{
    //Entity code
}

To work with your context.

Community
  • 1
  • 1
DanielV
  • 2,076
  • 2
  • 40
  • 61
  • 1
    Thanks looking at this, I am out of town with no access to a computer but I will look into this more when I get back. Thank you. – Steve Jul 26 '15 at 03:33