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

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

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

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


当前回答

我得到了这个异常,我设置id列为自动增量在我的数据库的表,然后它工作得很好

其他回答

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

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

我有这个问题与Mvc身份注册新用户,而不是:

var result = await UserManager.CreateAsync(user);

我正在做:

var result = await UserManager.UpdateAsync(user);

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.

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

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
        }

对于那些使用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的问题的错误。