I have the following code. When I trace the code I see that City
is not null, it's values changes then SaveChanges
is called but changes are not saved. there are about hundreds of similar code in this project and all of them works. what the problem can be here?
using (Entities db = new Entities())
{
long id = (long)((string)data.data[i].id).ParseLong();
City city = db.Cities.FirstOrDefault(c => c.Id == id);
if (city != null)
{
city.FromLat = data.data[i].fromlat;
city.ToLat = data.data[i].tolat;
city.FromLng = data.data[i].fromlng;
city.ToLng = data.data[i].tolng;
if (city.FromLat > city.ToLat) More.Swap(ref city.ToLat, ref city.FromLat);
if (city.FromLng > city.ToLng) More.Swap(ref city.FromLng, ref city.ToLng);
db.SaveChanges();
}
}
You haven't provided your model, but using the ref
keyword in these lines:
if (city.FromLat > city.ToLat) More.Swap(ref city.ToLat, ref city.FromLat);
if (city.FromLng > city.ToLng) More.Swap(ref city.FromLng, ref city.ToLng);
clearly indicates that FromLat
, ToLat
, FromLng
and ToLng
members are fields , thus not mapped to database columns. Make them properties and use different code for swapping (a bit longer, but working):
if (city.FromLat > city.ToLat) { var temp = city.FromLat; city.FromLat = city.ToLat; city.ToLat = temp; };
if (city.FromLng > city.ToLng) { var temp = city.FromLng; city.FromLng = city.ToLng; city.ToLng = temp; };
You did not add the item to its collection ( db.Cities.Add(city)
).
If you want to update the entity:
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
db.Entry(city).State = EntityState.Modified;
Should do the trick.
Add this right before savechanges
Try setting the state to modified via
db.Entry(city).State = System.Data.Entity.EntityState.Modified;
Or you can manually set each field that has changed as modified.
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.