4
votes

Following is the error message I get:

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.

My model consists of few columns, among them two columns which make up the primary key clustered:

[Key]
[Column(Order = 0)]
public string SourceName { get; set; }
[Key]
[Column(Order = 1)]
public string SourceType { get; set; }

Code to update using Entity Framework:

 _Entities.SourceInfoes.Attach(entity);
 _Entities.Entry(entity).State = EntityState.Modified;
 _Entities.SaveChanges();

Can some one help me on how to solve the exception above?

2
is your "Update" function in any for loop or timers? Most of the time, I noticed this error occurs when _Entities.SaveChanges() is currently being executed (but not completed yet) and at the same time, there might be either EF READ is taking place to same row (same record) . Its hard to help with these code snippets. - sam
Maybe optimistic concurrency was actually configured and entity is attached without (or with an expired) concurrency token. Not enough details to answer this question. - Gert Arnold

2 Answers

0
votes

Before saving your changes, are you making sure that all not-null properties have a value?

In my case I had to add a hidden value in the view, so the primary key would be posted back to the server.

@Html.HiddenFor(model => model.Id)
0
votes

For me, the problem was Unique Index on some of the columns in my database. Violating the index was causing this error to be displayed.

But when I was searching for the solution I found there can be other reasons for this error also , like make sure key have values and are not null , check concurrence setting for the column .