Hello, I am using Entity framework in my asp.net MVC project, when I try to delete any row using Entity framework, I am getting following error
Store update, insert, or delete statement affected an unexpected number of rows (0).
Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Here is the sample code, which is throwing this error
using (TestNewDBEntities testdb = new TestNewDBEntities())
{
Blogs item = testdb.Blogs.First(i => i.BID == id);
testdb.DeleteObject(item); //error
testdb.SaveChanges();
}
How to solve this issue?
Thanks
Here are the possible causes of the issue:
EntityState.Modified
then it will throw this error as it doesn't yet exist in the database.
@Html.HiddenFor(a=>a.Id)
in your form data, where Id is Primary Key.
So mostly, the error is related to Database table that was affected didn't have any Primary Key in the SQL Server Database structure, while in the EntityFramework table another Field was marked as Primary key, as EntityFramework requires all entities to have at least one Primary key, so mostly it is your database Design issue considering issues 1/2 mentioned
Solution: Solve it by adding a primary key to the database table, and making it an IDENTITY column.
If we consider above-mentioned point 3 for this error check your form and add required PK as hidden value
If issue is related to above mentioned last point(4th one), you can take a look at the detailed solution provided here https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
You can also get this error when you are trying to use DateTime.Now
as Primary key in Database table.
Because when saving DateTime.Now
, Entity framework would insert the value with millisecond precision but SQL Server will round it off, which will throw this error.
The solution is to truncate the milliseconds from DateTime.Now
before inserting value in DB table.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly