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

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

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

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


当前回答

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

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();
    }
}

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

其他回答

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

这样做:

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

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

希望这能有所帮助。

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

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

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

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.

我今天遇到了一个类似的问题,我将在这里记录它,因为它不完全是乐观并发错误。

我正在将一个旧系统转换为一个新的数据库,它有几千个实体,我必须把它们脚本转移到新系统。然而,为了帮助理智,我选择保持原始的唯一id,所以是注入到新对象,然后尝试保存它。

我遇到的问题是,我使用MVC脚手架来创建基本存储库,他们在他们的UpdateOrInsert方法中有一个模式,基本上是在添加新实体或将其状态更改为modified之前检查是否设置了Key属性。

因为设置了Guid,所以它试图修改数据库中实际上不存在的行。

我希望这能帮助到其他人!