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

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

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

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


当前回答

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

这样做:

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

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

希望这能有所帮助。

其他回答

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.

我也有同样的问题。 在我的情况下,我试图更新主键,这是不允许的。

我在使用Telerik的RadGrid时遇到了这个问题。我将主键设置为只读的绑定列。如果列是display="false",它会工作得很好,但readonly="true"导致了问题。我通过将绑定列display=false并添加一个单独的模板列来解决这个问题

<telerik:GridBoundColumn HeaderText="Shouldnt see" Display="false" 
     UniqueName="Id" DataField="Id">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Id" UniqueName="IdDisplay">
    <ItemTemplate>
        <asp:Label ID="IDLabel" runat="server" 
            Text='<%# Eval("Id") %>'></asp:Label>                               
    </ItemTemplate>
</telerik:GridTemplateColumn> 

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

context.Users.Attach(orderer);

with

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

只是确保表和形式都有主键和edmx更新。

我发现更新期间的任何错误通常是因为: —表中没有主键 -在编辑视图/表单中没有主键(例如@Html.HiddenFor(m=> m.d id)