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";
Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.
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 .
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.
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.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With