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

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

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

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


当前回答

我也遇到了同样的问题。

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

其他回答

我在使用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> 

如果您试图插入一个唯一的约束情况,也会发生这种情况,即如果每个雇主只能有一种类型的地址,而您试图插入第二个具有相同类型的相同雇主的地址,您将遇到相同的问题。

OR

如果所有被赋值的对象属性,都被赋值与之前相同,也会发生这种情况。

        using(var db = new MyContext())
        {
            var address = db.Addresses.FirstOrDefault(x => x.Id == Id);

            address.StreetAddress = StreetAddress; // if you are assigning   
            address.City = City;                   // all of the same values
            address.State = State;                 // as they are
            address.ZipCode = ZipCode;             // in the database    

            db.SaveChanges();           // Then this will throw that exception
        }

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

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.

以上的答案都没有完全涵盖我的情况和解决方案。

在MVC5控制器中抛出错误的代码:

        if (ModelState.IsValid)
        {
            db.Entry(object).State = EntityState.Modified; 
            db.SaveChanges(); // line that threw exception
            return RedirectToAction("Index");
        }

当我从Edit视图保存对象时,我收到了这个异常。它抛出它的原因是,当我回去保存它时,我修改了构成对象主键的属性。因此,将其状态设置为Modified对EF没有任何意义——它是一个新条目,而不是先前保存的条目。

你可以通过以下两种方法来解决这个问题:A)修改save调用来添加对象;B)在edit时不要更改主键。B)。

当我在数据库中删除一些行(在循环中),并在同一表中添加新的行时,我得到了这个错误。

我的解决方案是,在每个循环迭代中动态地创建一个新的上下文