Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 2 months ago 21
C# Question

Entity Framework SaveChanges is called but its not working

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

Answer

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; };
Comments