Entity framework save changes

c# ef-code-first entity-framework-6

Question

Does saving changes after a read-only operation serve any purpose? If nothing changes once the entities are loaded into the cache, should save changes be called before disposing?

1
6
2/15/2016 7:27:38 AM

Accepted Answer

zzz-5 to zzz:

Saves all changes made in this context to the underlying database.

No, calling is pointless.SaveChanges if you haven't adjusted your context in any way.

You can read here more about this in detail.

An entity can be in one of five states as defined by the EntityState enumeration. These states are:

  • Added: the entity is being tracked by the context but does not yet exist in the database
  • Unchanged: the entity is being tracked by the context and exists in the database, and its property values have not changed from the values in the database
  • Modified: the entity is being tracked by the context and exists in the database, and some or all of its property values have been modified
  • Deleted: the entity is being tracked by the context and exists in the database, but has been marked for deletion from the database the next time SaveChanges is called
  • Detached: the entity is not being tracked by the context

SaveChanges does different things for entities in different states:

  • Unchanged entities are not touched by SaveChanges. Updates are not sent to the database for entities in the Unchanged state.
  • Added entities are inserted into the database and then become Unchanged when SaveChanges returns.
  • Modified entities are updated in the database and then become Unchanged when SaveChanges returns.
  • Deleted entities are deleted from the database and are then detached from the context.
7
2/15/2016 7:40:52 AM

Popular Answer

No need to make a callSaveChanges() If you don't:

  1. Add
  2. Update
  3. Delete


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow