简体   繁体   中英

Entities may have been modified or deleted since entities were loaded. when using db.Entry(entity).State = EntityState.Modified;SaveChanges()

When looping through database rows and editing data with each iteration using the following code

 var entities = db.entities.Where(l => l.id > 28181 && l.id < 28425 && l.Geometry == null).ToList();
        HttpClient client = new HttpClient();
        HttpResponseMessage response = new HttpResponseMessage();
        foreach (model entity in entities)
        {

            string area = entity.address + " " + entity.city + " " + country;
            var address = String.Format("https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyArOWaWq_xXjAm68DlFFFqoxK7Z_ggYk9E&address=" + gebied);
            response = await client.GetAsync(address);
            var bekijk = response.StatusCode;
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsStringAsync();
                var jObject = Newtonsoft.Json.Linq.JObject.Parse(data.Result);
                string status = jObject["status"].ToObject<string>();
                if (status== "OK")
                {
                    var geometryLocation = jObject["results"][0]["geometry"]["location"];
                    string lat = geometryLocation["lat"].ToObject<string>();
                    string lon = geometryLocation["lng"].ToObject<string>();
                    entity.Geometry = System.Data.Entity.Spatial.DbGeometry.FromText("POINT(" + lat + " " + lon + ")");
                    entity.Latitude = Convert.ToDecimal(lat.Replace('.', ','));
                    entity.Longitude = Convert.ToDecimal(lon.Replace('.', ','));
                    db.Entry(entity).State = EntityState.Modified;
                }

            }

        }
        db.SaveChanges();

At db.SaveChanges(); an error occurs. Namely

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.

I've tried the solutions I saw on stackoverflow but nothing did the trick. Does anyone have any clues? Thanks in advance.

Assigning the values and saving it in a different method somehow fixes it. Can someone please tell me why?

    public async void FirstMethod()
    {

        var entities = db.entities.ToList();

        HttpClient client = new HttpClient();
        HttpResponseMessage response = new HttpResponseMessage();
        foreach (var entity in entities)
        {

            string area= entity.address + " " + entity.city + " " + land;
            var address = String.Format("https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyArOWaWq_xXjAm68DlFFFqoxK7Z_ggYk9E&address=" + area);
            response = await client.GetAsync(address);

            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsStringAsync();
                var jObject = Newtonsoft.Json.Linq.JObject.Parse(data.Result);
                string status = jObject["status"].ToObject<string>();

                if (status == "OK")
                {
                    var geometryLocation = jObject["results"][0]["geometry"]["location"];
                    string lat = geometryLocation["lat"].ToObject<string>();
                    string lon = geometryLocation["lng"].ToObject<string>();
                    SecondMethod(lat+" "+lon ,entity);
                }
            }
        }
    }


    public void SecondMethod(string preometry, model entity)
    {
        entity.Geometry = System.Data.Entity.Spatial.DbGeometry.FromText("POINT(" + preometry + ")");
        string[] latLon = preometry.Split(' ');
        entity.Latitude = Decimal.Parse(latLon[0].Replace(".", ","));
        entity.Longitude = Decimal.Parse(latLon[1].Replace(".", ","));
        db.Entry(entity).State = EntityState.Modified;
        db.SaveChanges();
    }

Did you try to update the entities manually?

Using the Package Manager Console:

PM> Add-Migration MyMigration
...
PM> Update-Database

This may help: Automatic Code First Migrations

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