views:

1055

answers:

2

I am using Entity Framework to populate a grid control. It 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?

A: 

That's a side-effect of a feature called optimistic concurrency.

Not 100% sure how to turn it on/off in Entity Framework but basically what it's telling you is that between when you grabbed the data out of the database and when you saved your changes someone else has changed the data (Which meant when you went to save it 0 rows actually got updated). In SQL terms their UPDATE query's where clause contains the original value of every field in the row, and if 0 rows are affected it knows something's gone wrong.

The idea behind it is that you won't end up overwriting a change your application didn't know has happened - it's basically a little safety measure thrown in by .NET on all your updates.

Odds are it's within your own logic that it's happening if it's consistent (EG: You're actually updating the data yourself in another method in-between the select and the update), but it could be simply a race condition between two applications.

Tim Schneider
This is happening in a single-user environment (on my dev machine) so I don't think it could be a race condition. I am binding to a custom grid control with an EntityDataSource so I'm not sure exactly what's happening behind the scenes, but I don't have any extra code of my own that is modifying the tables. Is there a way to change this concurrency setting?
strongopinions
I think you can on a per-column basis in your entity model (It's in the properties window), but the thing is that'll just prevent you seeing the error and it'll still not update anything. Are you able to view the SQL commands going to your database (EG: SQL Server Profiler for MSSQL)? This way you could see what update it's generated and should be able to see why that update doesn't affect any rows.
Tim Schneider
A: 

You need to explicitly include a BoundField of the primary key. If you don't want the user to see the primary key, you have to hide it via css:

    <asp:BoundField DataField="Id_primary_key" ItemStyle-CssClass="hidden" 
HeaderStyle-CssClass="hidden" />

Where 'hidden' is a class in css that has it's display set to 'none'.

Paulo