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

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

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

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


当前回答

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

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

其他回答

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

偶尔错误:

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

检查你是否忘记了GridView中的“DataKeyNames”属性。 当在GridView中修改数据时,它是必须的

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx

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

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
        }

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

对于那些使用AutoMapper的人 如果您正在更新一个实体,该实体具有指向另一个实体(或多个实体)的外键,请确保所有的外实体都将其主键设置为数据库生成(或对MySQL自动递增)。

例如:

public class BuyerEntity
{
    [Key]
    public int BuyerId{ get; set; }

    public int Cash { get; set; }

    public List<VehicleEntity> Vehicles { get; set; }

    public List<PropertyEntity> Properties { get; set; }

}

Vehicles和Properties存储在不同于Buyers的表中。当你添加一个新的买家时,AutoMapper和EF会自动更新车辆和属性表,所以如果你没有在这些表上设置自动增量(就像我没有),那么你会看到来自OP的问题的错误。