简体   繁体   中英

Entities SaveChanges throws exception

Im saving some locations/cities in my database. Thing is everything worked fine until i added one new column to the table in the database and updated the datamodel in my project.

My locations/cities DOES get saved althrough my this._entities.SaveChanges(); throws an execption that goes something like:

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.

I dont really know whats the problem since it worked before and this changes should not affect it really...

Here's some code:
First off i get all the objects into currentLocation. I loop them through a foreach to add item to method Add(). Last i call for _entites.SaveChanges(). Everything gets saved but i get an error...

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

I suspect the exception may occur due to two different problems:

1- In previous calls, you have already retrieved locations; and you are trying to insert same values. 2- the primary key of location entities retrieved from web service are not unique.

In order to determine the exact problem, please check inner exceptions of the displayed exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM