Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context.SaveChanges return 0 when updated without any change

context.SaveChanges() returns 0 if I only hit the update button. If I don't change anything and just hit the update button, it returns 0. I am checking on the value which is returned by SaveChanges. Which are the conditions where SaveChanges returns 0. What are the return values indicate?

Following is my code.

int returnValue = CS.SaveChanges();
                   return returnValue == 1 ? "User profile has been updated successfully" : "Unable to update";
like image 892
user2998990 Avatar asked Jan 16 '15 05:01

user2998990


People also ask

What does DbContext SaveChanges return?

Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.

What is context SaveChanges?

The SaveChanges method of the DbContext prepares the Insert , Update & Delete Queries. It does so by tracking the changes to each of the entities' context is tracking. Whenever we query the database for entities, the context retrieves them and mark the entity as Unchanged .

Does SaveChanges commit?

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.


1 Answers

According to the documentation the return value is the number of objects updated in the context:

Return Value
Type: System.Int32
The number of objects written to the underlying database.

So your method could look like this:

int returnValue = CS.SaveChanges();
return returnValue > 0 ? 
    String.Format("{0} User profiles have been updated successfully.", returnvalue) : 
    "No updates have been written to the database.";
like image 138
Marco Avatar answered Sep 28 '22 01:09

Marco