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

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

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

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


当前回答

我在一个缺少主键并且有一个DATETIME(2,3)列的表上遇到了这个问题(因此实体的“主键”是所有列的组合)…执行插入时,时间戳有一个更精确的时间(2018-03-20 08:29:51.8319154),被截断为(2018-03-20 08:29:51.832),因此对关键字段的查找失败。

其他回答

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

哇,很多答案,但我得到这个错误时,我做了一些稍微不同,没有人提到。

长话短说,如果您创建了一个新对象,并告诉EF它使用EntityState进行了修改。修改后,它将抛出这个错误,因为它还不存在于数据库中。这是我的代码:

MyObject foo = new MyObject()
{
    someAttribute = someValue
};

context.Entry(foo).State = EntityState.Modified;
context.SaveChanges();

是的,这看起来很愚蠢,但它的出现是因为有问题的方法以前已经创建了foo,现在它只传递了someValue给它,并创建了foo自己。

很容易修复,只需改变EntityState。修改为EntityState。添加或更改整行为:

context.MyObject.Add(foo);

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.

我在使用异步方法时偶尔会得到这个错误。自从我切换到同步方法后就没有发生过。

偶尔错误:

[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public async Task<IHttpActionResult> Delete(int id, int customerId)
{
    var file = new Models.File() { Id = id, CustomerId = customerId };
    db.Files.Attach(file);
    db.Files.Remove(file);

    await db.SaveChangesAsync();

    return Ok();
}

一直有效:

[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public IHttpActionResult Delete(int id, int customerId)
{
    var file = new Models.File() { Id = id, CustomerId = customerId };
    db.Files.Attach(file);
    db.Files.Remove(file);

    db.SaveChanges();

    return Ok();
}

在同一个上下文中使用SaveChanges(false)和后来的SaveChanges()时得到此错误,在一个工作单元中,从两个表中删除多行(在上下文中)(SaveChanges(false)在其中一个删除中。然后在调用函数中,SaveChanges()被调用为....解决方案是删除不必要的SaveChanges(false)。