我正在使用实体框架来填充网格控件。有时当我进行更新时,我得到以下错误:

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

我不知道怎么复制这个。但这可能和我更新的时间间隔有关系。有人见过这个吗,或者有人知道错误消息指的是什么吗?

编辑:不幸的是,我不再有自由重现我在这里遇到的问题,因为我离开了这个项目,不记得我最终是否找到了解决方案,是否有其他开发人员修复了它,或者是否我绕过了它。因此我不能接受任何回答。


当前回答

当附加一个数据库中不存在的对象时,我得到了这个异常。我假定对象是从单独的上下文中加载的,但如果这是用户第一次访问站点,则从头创建对象。我们有自动递增的主键,所以我可以替换

context.Users.Attach(orderer);

with

if (orderer.Id > 0) {
    context.Users.Attach(orderer);
}

其他回答

我也有这个错误。在某些情况下,实体可能不知道您正在使用的实际数据库上下文,或者模型可能不同。为此,设置:EntityState.Modified;EntityState.Added;

这样做:

if (ModelState.IsValid)
{
context.Entry(yourModelReference).State = EntityState.Added;
context.SaveChanges();
}

这将确保实体知道你正在使用或添加正在使用的状态。此时,需要设置所有正确的模型值。小心不要丢失任何可能在后台所做的更改。

希望这能有所帮助。

在同一个上下文中使用SaveChanges(false)和后来的SaveChanges()时得到此错误,在一个工作单元中,从两个表中删除多行(在上下文中)(SaveChanges(false)在其中一个删除中。然后在调用函数中,SaveChanges()被调用为....解决方案是删除不必要的SaveChanges(false)。

Got the same problem when removing item from table(ParentTable) that was referenced by another 2 tables foreign keys with ON DELETE CASCADE rule(RefTable1, RefTable2). The problem appears because of "AFTER DELETE" trigger at one of referencing tables(RefTable1). This trigger was removing related record from ParentTable as result RefTable2 record was removed too. It appears that Entity Framework, while in-code was explicitly set to remove ParentTable record, was removing related record from RefTable1 and then record from RefTable2 after latter operation this exception was thrown because trigger already removed record from ParentTable which as results removed RefTable2 record.

在编辑时,将实体的id或主键作为视图中的隐藏字段

ie

      @Html.HiddenFor(m => m.Id)

这样问题就解决了。

此外,如果你的模型包括未使用的项目,也包括它,并张贴到控制器

我也有同样的问题,@webtrifusion的答案帮助我找到了解决方案。

我的模型使用实体ID上的绑定(排除)属性,这导致实体ID的值在HttpPost上为零。

namespace OrderUp.Models
{
[Bind(Exclude = "OrderID")]
public class Order
{
    [ScaffoldColumn(false)]
    public int OrderID { get; set; }

    [ScaffoldColumn(false)]
    public System.DateTime OrderDate { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Username { get; set; }
    }
}