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

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

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

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


当前回答

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

在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)。

其他回答

我遇到了这个问题,这是由于实体的ID(键)字段没有设置造成的。因此,当上下文去保存数据时,它找不到ID = 0。请确保在更新语句中放置断点,并验证实体的ID是否已设置。

来自Paul Bellora的评论

我也遇到过同样的问题,因为忘记包含隐藏ID 在.cshtml编辑页面中输入

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

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.

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

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

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

我将抛出这个,以防有人在并行循环中工作时遇到这个问题:

Parallel.ForEach(query, deet =>
{
    MyContext ctx = new MyContext();
    //do some stuff with this to identify something
    if(something)
    {
         //Do stuff
         ctx.MyObjects.Add(myObject);
         ctx.SaveChanges() //this is where my error was being thrown
    }
    else
    {
        //same stuff, just an update rather than add
    }
}

我把它改成如下:

Parallel.ForEach(query, deet =>
{
    MyContext ctxCheck = new MyContext();
    //do some stuff with this to identify something
    if(something)
    {
         MyContext ctxAdd = new MyContext();
         //Do stuff
         ctxAdd .MyObjects.Add(myObject);
         ctxAdd .SaveChanges() //this is where my error was being thrown
    }
    else
    {
        MyContext ctxUpdate = new MyContext();
        //same stuff, just an update rather than add
        ctxUpdate.SaveChanges();
    }
}

不确定这是否是“最佳实践”,但它通过让每个并行操作使用自己的上下文来解决我的问题。