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

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

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

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


当前回答

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

其他回答

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

这样做:

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

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

希望这能有所帮助。

只是确保表和形式都有主键和edmx更新。

我发现更新期间的任何错误通常是因为: —表中没有主键 -在编辑视图/表单中没有主键(例如@Html.HiddenFor(m=> m.d id)

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

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.

在编辑时,将实体的id或主键作为视图中的隐藏字段

ie

      @Html.HiddenFor(m => m.Id)

这样问题就解决了。

此外,如果你的模型包括未使用的项目,也包括它,并张贴到控制器

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