Eitan Eitan - 2 months ago 5x
C# Question

DbContext.SaveChanges() is not updating the database

I'm trying to save an entity to the database using entity framework. I have this code which handles the update of the object:


Afterwards I call:


(I'm using the Unit Of Work pattern with MVC)

The entity I want to add has the state "Modified". Calling the SaveChanges doesn't throw an exception but the return value is 0 and the row in the DB isn't updated. Any idea why this is happening?

P.S. I use the same context to retrieve the entity and then later on to save it.

P.P.S I can post code, I don't know which code would be relevant though because I don't know where the problem originates.


I am assuming that the entity is already attached by being a result of a previous query, or by adding it as a new entity via Add.

When you attached the entity via Attach, the state was changed to Unchanged.

Quoting from this reference:

Note that entities that are already in the context in some other state will have their state set to Unchanged

Since the object was already in the context, you don't have to attach it. Simply modify the entity and call SaveChanges.