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

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

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

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


当前回答

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

context.Users.Attach(orderer);

with

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

其他回答

检查你是否忘记了GridView中的“DataKeyNames”属性。 当在GridView中修改数据时,它是必须的

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx

我也有同样的问题。但这是我自己的失误。实际上,我是保存一个对象,而不是添加它。这就是矛盾所在。

  @Html.HiddenFor(model => model.RowVersion)

我的rowversion是null,所以必须将它添加到视图中 这解决了我的问题

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.

该问题是由以下两种原因之一引起的:-

You tried to update a row with one or more properties are Concurrency Mode: Fixed .. and the Optimistic Concurrency prevented the data from being saved. Ie. some changed the row data between the time you received the server data and when you saved your server data. You tried to update or delete a row but the row doesn't exist. Another example of someone changing the data (in this case, removing) in between a retrieve then save OR you're flat our trying to update a field which is not an Identity (ie. StoreGeneratedPattern = Computed) and that row doesn't exist.