I am using Entity Framework to populate a grid control. Sometimes when I make updates I get the 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.
I can't figure out how to reproduce this. But it might have something to do with how close together I make the updates. Has anyone seen this or does anyone know what the error message refers to?
Edit: Unfortunately I am no longer at liberty to reproduce the problem I was having here, because I stepped away from this project and don't remember if I eventually found a solution, if another developer fixed it, or if I worked around it. Therefore I cannot accept any answers.
I ran into this and it was caused by the entity's ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity's ID has been set.
From Paul Bellora's comment
When the accepted answer said "it won't end up overwriting a change that your application didn't know has happened", I was skeptic because my object was newly created. But then it turns out, there was an
INSTEAD OF UPDATE, INSERT- TRIGGER
attached to the table which was updating a calculated column of the same table.Once I change this to
AFTER INSERT, UPDATE
, it was working fine.I got this same error because part of the PK was a datetime column, and the record being inserted used DateTime.Now as the value for that column. Entity framework would insert the value with millisecond precision, and then look for the value it just inserted also with millisecond precision. However SqlServer had rounded the value to second precision, and thus entity framework was unable to find the millisecond precision value.
The solution was to truncate the milliseconds from DateTime.Now before inserting.
The issue is caused by either one of two things :-
Concurrency Mode: Fixed
.. and the Optimistic Concurrency prevented the data from being saved. Ie. some changed the row data between the time you received the server data and when you saved your server data.StoreGeneratedPattern = Computed
) and that row doesn't exist.None of the above answers quite covered my situation and the solution to it.
Code where the error was thrown in MVC5 controller:
I received this exception when I was saving an object off an Edit view. The reason it threw it was because when I went back to save it, I had modified the properties that formed the primary key on the object. Thus, setting its state to Modified didn't make any sense to EF - it was a new entry, not a previously saved one.
You can solve this by either A) modifying the save call to Add the object, or B) just don't change the primary key on edit. I did B).