实体SaveChanges抛出异常

时间:2013-01-12 10:18:24

标签: c# asp.net-mvc database asp.net-mvc-3

我在我的数据库中保存了一些位置/城市。事情一切正常,直到我在数据库中向表中添加了一个新列并更新了项目中的数据模型。

我的位置/城市通过我的this._entities.SaveChanges();得到的保存会引发类似的行为:

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message:AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.

我真的不知道这个问题是什么,因为它之前有效,这种变化不应该影响它......

这是一些代码:
首先,我将所有对象都放入currentLocation。 我通过foreach循环它们以将项添加到方法Add()。 最后我呼吁_entites.SaveChanges()。一切都得到了保存,但我得到了一个错误......

           var webService = new WeatherWebService();
            currentLocation = webService.FindLocation(city);

            // ...save the user in the database.
            foreach (var item in currentLocation)
            {
                this._repository.Add(item);
            }

            this._repository.Save();

    public override void Add(Location location)
    {
        this._entities.Locations.AddObject(location);
    }

    public override void Save()
    {
        this._entities.SaveChanges();
    }

1 个答案:

答案 0 :(得分:0)

我怀疑由于两个不同的问题可能会发生异常:

1-在之前的通话中,您已经检索了位置;并且您正在尝试插入相同的值。 2-从Web服务检索的位置实体的主键不是唯一的。

为了确定确切的问题,请检查显示的异常的内部异常。

相关问题