编辑Id - 存储更新,插入或删除语句影响了意外的行数(0) [英] Edit Id - Store update, insert, or delete statement affected an unexpected number of rows (0)

查看:340
本文介绍了编辑Id - 存储更新,插入或删除语句影响了意外的行数(0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要编辑我的主键字段在我的编辑页面一行,我得到错误


存储更新,插入或删除语句
影响了意外数量的行(0)。
实体可能已被修改或删除
,因为实体被加载。刷新ObjectStateManager条目。


当我不更改主键字段时,我可以将我所有的其他更改保存到我的数据库。 p>

这是我的编辑功能。

  // 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)
{
//记录错误(在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);
}

我如何去编辑主键,或者我接近这个错误的方式?

解决方案

当使用像实体框架这样的ORM时,UPDATE命令基本上是这样组合的:

 更新表
SET ChangedCol = ChangedVal
WHERE PrimaryKeyCol = PrimaryKeyValAtLoadTime
pre>

之后,它会检查受影响的行数以匹配预期值。



所以当你尝试更改PK更新命令将更新没有行,检查将失败。



真正的问题是:为什么要更改主键值?


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?

解决方案

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?

这篇关于编辑Id - 存储更新,插入或删除语句影响了意外的行数(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆