Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity Framework's DbContext save changes if no changes were made?

Tags:

I could not find an answer on the Internet.

Let's suppose I have a DbContext, and I just select all the entities from it. I don't add, update or delete any entity on the DbSet.

If I call SaveChanges afterwards on the DbSet. Does it actually waste resources establishing a connection and other stuff even If I did not made any changes to the DbSet?

Is it smart enough to detect if a change was made or not, and behave differently?

like image 904
Matias Cicero Avatar asked Nov 21 '14 12:11

Matias Cicero


People also ask

How do I save changes in Entity Framework?

Entity Framework Core Save Changes to the database using the SaveChanges method of DbContext. When we use the SaveChanges it prepares the corresponding insert , update , delete queries. It then wraps them in a Transaction and sends them to the database. If any of the queries fails all the statements are rolled back.

How does DbContext change state of entity?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.

Which of the following Entity Framework method saves all changes made in this context to the underlying database?

SaveChanges() Saves all changes made in this context to the database. This method will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database.


1 Answers

It uses EntityState to determine that there is nothing to commit and so does not waste resources.

http://msdn.microsoft.com/en-us/library/system.data.entitystate%28v=vs.110%29.aspx

like image 174
Kaido Avatar answered Oct 16 '22 22:10

Kaido