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

asp.net-mvc asp.net-mvc-4 c# entity-framework

Question

So I need to be able to edit my primary key field in my edit page for a row, I get the error

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

When I don't change the primary key field I can save all my other changes to my database.

This is my edit function.

//edit - post
[HttpPost]
public ActionResult ActiveCampaignsEdit(ActiveCampaign activecampaign)
{
  try
  {
    if (ModelState.IsValid)
    {
      db.Entry(activecampaign).State = EntityState.Modified;
      db.SaveChanges();
      return RedirectToAction("ActiveCampaigns");
    }
  }
  catch (DataException err)
  {
    //Log the error (add a variable name after DataException)
    ModelState.AddModelError(string.Empty, err.Message);
  }
  ViewBag.TypesList = new SelectList(db.Types, "TypeId", "TypeName");
  ViewBag.CaptureFormsList = new SelectList(db.CaptureForms, "Id", "Name");
  ViewBag.AssignedUsersList = new SelectList(db.Users, "Id", "Username");
  return View(activecampaign);
}

How would I go about editing the Primary Key, or am I approaching this in the wrong way?

1
1
11/27/2012 3:40:33 PM

Accepted Answer

When using ORMs like Entity Framework, the UPDATE command is composed basically like this:

UPDATE table 
SET ChangedCol = ChangedVal 
WHERE PrimaryKeyCol = PrimaryKeyValAtLoadTime

Afterwards it checks the number of affected rows to match the expected value.

So when you try to change the PK the update command will update no row and the check will fail.

The real question is: Why do you want to change the primary key value?

3
11/27/2012 3:46:02 PM

Popular Answer

public void Save(object entity)
        {
            using (var transaction = Connection.BeginTransaction())
            {
            try
                    {
                        SaveChanges();
                        transaction.Commit();
                    }
                    catch (OptimisticConcurrencyException)
                    {
                        if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Deleted || ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Modified)
                            this.Refresh(RefreshMode.StoreWins, entity);
                        else if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Added)
                            Detach(entity);
                        AcceptAllChanges(); 
                        transaction.Commit();
                    }
            }
        }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow