使用以下代码循环遍历数据库行并使用每次迭代编辑数据时
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();
在db.SaveChanges();
发生错误。即
存储更新,插入或删除语句会影响意外的行数(0)。自实体加载以来,实体可能已被修改或删除。
我已经尝试过在stackoverflow上看到的解决方案,但没有做到这一点。有人有任何线索吗?提前谢谢。
答案 0 :(得分:0)
分配值并以其他方法保存它以某种方式修复它。 有人可以告诉我为什么吗?
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();
}
答案 1 :(得分:-1)
您是否尝试手动更新实体?
使用程序包管理器控制台:
PM> Add-Migration MyMigration
...
PM> Update-Database
这可能有所帮助:Automatic Code First Migrations