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

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

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

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


当前回答

我也遇到了同样的问题。

我使用EF 6,代码优先+迁移。 问题是我们的DBA在抛出错误的表上创建了一个约束。

其他回答

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.

在从模型优先改为代码优先之后,我开始得到这个错误。我有多个线程更新数据库,其中一些可能更新同一行。我不知道为什么我没有使用模型优先的问题,假设它使用不同的并发默认。

为了在一个地方处理它,知道它可能发生的条件,我在DbContext类中添加了以下重载:

using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

public class MyDbContext: DbContext {
...
        public int SaveChanges(bool refreshOnConcurrencyException, RefreshMode refreshMode = RefreshMode.ClientWins) {
            try {
                return SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex) {
                foreach (DbEntityEntry entry in ex.Entries) {
                    if (refreshMode == RefreshMode.ClientWins)
                        entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                    else
                        entry.Reload();
                }
                return SaveChanges();
            }
        }
}

然后在任何适用的地方调用SaveChanges(true)。

我也有同样的问题,@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; }
    }
}   

我还遇到了这个错误。问题原来是由我试图保存到的桌子上的触发器引起的。触发器使用了'INSTEAD OF INSERT',这意味着0行被插入到该表,因此出现了错误。幸运的是,在可能的情况下,触发器功能是不正确的,但我猜它可能是一个有效的操作,应该以某种方式在代码中处理。希望有一天这能帮助到别人。

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

ie

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

这样问题就解决了。

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