[Solved] Store update, insert, or delete statement affected an unexpected number of rows (0)

While working with the Entity Framework you might be facing issues like Store update, insert, or delete statement affected an unexpected number of rows (0). The Compete error is Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

For a Simple example please consider the following code where you are trying to update the user details using Entity Framework

db.Entry(tblUser).State = EntityState.Modified;
db.SaveChanges()

For the above example if you want to update the tblUser table then you must have an identity column value inside the tblUser Model and if you don’t have it ( means if you have some null value for the identity column or something different value which is not present yet in the database) then you might get the error Store update, insert, or delete statement affected an unexpected number of rows (0).

The Solution

The solution is very simple just add an Identity Column along with a valid value with is present in the database during the update and delete operation.

For the Insert operation with Entity Framework, we just have the Identity column, and Entity Framework automatically updates the identity column value after the db.SaveChanges().

Hope this will help you.

Happy Coding! 😃😊