Error "Entity Framework: Store update, insert, or delete statement affected an unexpected number of rows (0)"

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


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

How to solve this issue? 


Asked by:- neena
: 715 At:- 1/11/2018 2:53:16 PM
ASP.NET MVC Store update insert or delete statement affected an unexpected C# Entity-framework

1 Answers
profileImage Answered by:- pika

Here are the possible causes of the issue:

  1. It occurs when entity key(Primary key) is not set or it is set as 0, basically saving data with 0 PK or updating row which does not exist.
  2. If you create a new object and tell EF that it's modified using the EntityState.Modified then it will throw this error as it doesn't yet exist in the database.
  3. When you are editing a form and saving update form using EF but forgot to include @Html.HiddenFor(a=>a.Id) in your form data, where Id is Primary Key.
  4. Can be caused by concurrent changes occurring to the database at the same time.

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

At:- 1/12/2018 7:55:43 AM
great answer with proper details 0
By : manish - at :- 1/14/2018 3:15:49 PM
my issue was related to point 1, thanks 0
By : neena - at :- 1/16/2018 3:18:02 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *
