Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

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

Upvotes: 1

Views: 100

Answers (4)

Pentest Backtrack
Pentest Backtrack

Reputation: 1

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

Upvotes: 0

Ivan Stoev
Ivan Stoev

Reputation: 205539

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

Upvotes: 4

Donald Fraser
Donald Fraser

Reputation: 86

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.

Upvotes: 0

Vincentw
Vincentw

Reputation: 184

db.Entry(city).State = EntityState.Modified;

Should do the trick.

Add this right before savechanges

Upvotes: 0

Related Questions