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

左心房为你撑大大i 提交于 2020-01-05 07:21:26

问题


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:


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?




回答2:


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();
                    }
            }
        }


来源:https://stackoverflow.com/questions/13586995/edit-id-store-update-insert-or-delete-statement-affected-an-unexpected-numbe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!