356

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.

5
  • I got this error with the introduction of a SQL Server Row Level Security policy that allowed updates to a row into a state that could not be read back (an exclusive FILTER predicate with a permissive BLOCK predicate). EntityFramework requires the updated row to be read back after the update otherwise it assumes it was a concurrency error (at least when using optimistic concurrency).
    – xr280xr
    Apr 24, 2018 at 21:02
  • The problem could be incorrect scoping for your DBContext stackoverflow.com/questions/49154250/… (this example is for ASPNET Identity but applies for any context) Dec 17, 2018 at 23:33
  • Regardless of the context of this error it's a good idea to put a breakpoint wherever it is that the context is being instantiated. Were you expecting it to be instantiated once when you loaded a webpage but it's hitting that breakpoint 5 times? Then you probably have a race condition. Look at Request.Uri to see the actual request URL. In my case I had some tracking logic that was hitting my site and unnecessarily loading the context from the DB (and occasionally updating it too). So then the actual page I was debugging had had its data stomped upon by a stupid tracking code logic. Dec 17, 2018 at 23:44
  • add @Html.AntiForgeryToken() in view Feb 14, 2019 at 10:10
  • I can not give answer to the question now but I am getting this error when I am using the reverse poco generator(marketplace.visualstudio.com/…) and the issue was I don't have primary key set on the table. Adding primary key to table and updating model solves my problem. Mar 31, 2021 at 10:06

45 Answers 45

420

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

I had this exact issue, caused by forgetting to include the hidden ID input in the .cshtml edit page

15
  • 3
    +1 I was having same problem and this helped find the solution. Turns out I had [Bind(Exclude = "OrderID")] in my Order model which was causing the value of the entity's ID to be zero on HttpPost.
    – Dhaust
    Jan 23, 2012 at 2:07
  • 3
    That's exactly what I was missing. My object's ID was 0. Aug 16, 2012 at 21:18
  • 5
    @Html.HiddenFor(model => model.productID) -- worked perfect. I was missing the productID on the EDIT PAGE (MVC RAZOR)
    – Ravi Ram
    Aug 28, 2012 at 5:02
  • 2
    I had a similar issue but with a twist. For me the issue was I didn't have the sql table setup correctly. My primary key field was not set to auto increment. So EF would send the record I was trying to insert w/o a key which is fine if you remember to tell sql that field is an auto increment Identity field, which I forgot :<
    – Agile Noob
    Jan 6, 2013 at 19:36
  • 1
    Same issue but using a composite key. One of the key values was not set.
    – obaylis
    Feb 5, 2015 at 16:17
219

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 that your application didn't know has happened - it's basically a little safety measure thrown in by .NET on all your updates.

If it's consistent, odds are it's happening within your own logic (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.

8
  • 41
    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? Dec 4, 2009 at 0:16
  • 3
    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.
    – fyjham
    Dec 4, 2009 at 4:58
  • 9
    If the entity has a timestamp property, then make sure you have it stored in your view and make sure the entity populate the timestamp properly.
    – anIBMer
    Aug 29, 2013 at 23:54
  • I had a timestamp column and once I addressed the it, EF6.1 worked as expected, thanks for the tip @anelBMer
    – JQII
    Sep 17, 2014 at 21:53
  • 3
    If you use timestamps, tje object you want to delete needs the PK set and the RowVersion Property in order to update it successfully! I was setting the rowVersion (timestamp) property, after I have attached the object to the respective DbSet, that's why it didn't work. Good job!
    – Legends
    Mar 29, 2015 at 17:10
121

Wow, lots of answers, but I got this error when I did something slightly different that no on else has mentioned.

Long story short, if you create a new object and tell EF that its modified using the EntityState.Modified then it will throw this error as it doesn't yet exist in the database. Here is my code:

MyObject foo = new MyObject()
{
    someAttribute = someValue
};

context.Entry(foo).State = EntityState.Modified;
context.SaveChanges();

Yes, this seems daft, but it arose because the method in question used to have foo passed to it having been created earlier on, now it only has someValue passed to it and creates foo itself.

Easy fix, just change EntityState.Modified to EntityState.Added or change that whole line to:

context.MyObject.Add(foo);
1
  • Thanks for posting this. That was my problem too, I had copy-pasted some code that was setting the State to EntityState.Modified.
    – clayRay
    May 22, 2018 at 4:42
24

I was facing this same scaring error... :) Then I realized that I was forgetting to set a

@Html.HiddenFor(model => model.UserProfile.UserId)

for the primary key of the object being updated! I tend to forget this simple, but very important thingy!

By the way: HiddenFor is for ASP.NET MVC.

4
  • 3
    That seems like a security flaw, to store the UserId in the form, very prone to hackers...this should be populated afterwards from HttpContext.Current.User.Identity.Name
    – Serj Sagan
    Nov 22, 2013 at 21:19
  • @SerjSagan you're right... but as long you do some checks on the server side to confirm the UserId and current UserName you're good to go. Nov 22, 2013 at 22:49
  • 2
    My point is why even store that in the HiddenFor you'll need to get it from the HttpContext anyways... I would not put this property in the form at all, which would force me to always populate it server side...
    – Serj Sagan
    Nov 25, 2013 at 5:08
  • Thats not true: "Wow, lots of answers, but I got this error when I did something slightly different that no on else has mentioned." user webtrifusion mentioned your case!
    – HelloWorld
    Jun 29, 2020 at 12:43
16

The issue is caused by either one of two things :-

  1. You tried to update a row with one or more properties are 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.
  2. You tried to update or delete a row but the row doesn't exist. Another example of someone changing the data (in this case, removing) in between a retrieve then save OR you're flat our trying to update a field which is not an Identity (ie. StoreGeneratedPattern = Computed) and that row doesn't exist.
2
  • 1
    This could also be caused if all of the object properties that were assigned to, they were assigned with the same values as they had before.
    – Serj Sagan
    Nov 29, 2013 at 19:46
  • +1 for 2nd one. I had StoreGeneratedPattern = None, changing to StoreGeneratedPattern = Identity resolved the issue. Thanks
    – tkt986
    May 27, 2017 at 16:46
16

Check whether you forgot the "DataKeyNames" attribute in the GridView. it's a must when modifying data within the GridView

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx

2
  • +1. Perfect and simple solution for me. I am binding GridView to EntityDataSource and did not set this to my primary key on the object.
    – Andez
    Aug 21, 2012 at 20:22
  • We know that Kendo UI does not support composite key, but in case I added new column that concat-ed my keys to one, what's happening then?
    – Branislav
    Nov 11, 2013 at 21:39
15

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.

4
  • 2
    We had the same problem except we were inserting into a Date column with a DateTime value
    – adam0101
    Jan 25, 2016 at 16:29
  • 1
    Same here. We had a data warehouse record and were using the timestamp as part of the key. The timestamp in the data warehouse was a SQL DateTime, but the timestamp in C# was not matching. I changed the SQL data type to DateTime2(7), updated the EF model, and all was fixed.
    – mmcfly
    Aug 30, 2018 at 21:04
  • Changing the column to Datetime2(7) worked for me too. Thanks @mmcfly
    – Dzejms
    Sep 18, 2018 at 16:24
  • I ended up using the solution here to truncate off the milliseconds.
    – Timothy G.
    Jan 16 at 18:31
10

I was having same problem and @webtrifusion's answer helped find the solution.

My model was using the Bind(Exclude) attribute on the entity's ID which was causing the value of the entity's ID to be zero on HttpPost.

namespace OrderUp.Models
{
[Bind(Exclude = "OrderID")]
public class Order
{
    [ScaffoldColumn(false)]
    public int OrderID { get; set; }

    [ScaffoldColumn(false)]
    public System.DateTime OrderDate { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Username { get; set; }
    }
}   
1
  • Similar problem, for security reasons, I have Bind(include = some fields). ID was not in the list. Also I added it as a hidden input. Must have erased something generated by MVC or the ID was not there at all. Thanks for the help. Apr 12, 2017 at 19:33
10

I had the same problem, I figure out that was caused by the RowVersion which was null. Check that your Id and your RowVersion are not null.

for more information refer to this tutorial

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application

2
  • row version was null in my case
    – wickjon
    Feb 17, 2015 at 8:29
  • In my case I had accidentally removed the Id field in my [Bind(Include = properties)]. Add it back and it worked fine.
    – Caverman
    May 12, 2016 at 1:09
9

I also came across this error. The problem it turned out was caused by a Trigger on the table I was trying to save to. The Trigger used 'INSTEAD OF INSERT' which means 0 rows ever got inserted to that table, hence the error. Luckily in may case the trigger functionality was incorrect, but I guess it could be a valid operation that should somehow be handled in code. Hope this helps somebody one day.

4
  • 2
    Entity can be tricked into believing that rows were added by returning a SELECT statement (with the primary key column) from the trigger.
    – jahu
    Feb 9, 2016 at 15:39
  • 2
    To expand on the comment by @jahu, I had to get an actual id of the newly inserted item to be returned from my trigger and the column name has to match the trigger table's identity column (in my case, actually a view so it didn't have an identity of its own but I had tricked the edmx into believing it did). My trigger was doing an insert into a separate table, so I just added this last line to my trigger: SELECT SCOPE_IDENTITY() as MyViewId Jun 28, 2016 at 23:10
  • Also see this question: stackoverflow.com/questions/5820992/…
    – J. Polfer
    Aug 24, 2016 at 15:50
  • In my case I was doing a delete operation on entities in a child collection but there was a trigger on delete for one of the child entities that caused another of the child entities to be deleted. This caused the error since N - 1 rows were affected due to the trigger deleting one of the child entities itself before entity framework tried to delete it.
    – skeletank
    Oct 12, 2017 at 17:39
8

While editing include the id or primary key of the entity as a hidden field in the view

ie

      @Html.HiddenFor(m => m.Id)

that solves the problem.

Also if your model includes non-used item include that too and post that to the controller

8

I started getting this error after changing from model-first to code-first. I have multiple threads updating a database where some might update the same row. I don't know why I didn't have a problem using model-first, assume that it uses a different concurrency default.

To handle it in one place knowing the conditions under which it might occur, I added the following overload to my DbContext class:

using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

public class MyDbContext: DbContext {
...
        public int SaveChanges(bool refreshOnConcurrencyException, RefreshMode refreshMode = RefreshMode.ClientWins) {
            try {
                return SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex) {
                foreach (DbEntityEntry entry in ex.Entries) {
                    if (refreshMode == RefreshMode.ClientWins)
                        entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                    else
                        entry.Reload();
                }
                return SaveChanges();
            }
        }
}

Then called SaveChanges(true) wherever applicable.

2
  • 1
    OK, everyone else is complaing about the issue, showing how they can trigger it etc, but this answer has a cool answer. I use a continue update model (no save button here baby) and was getting this on grid updates when the EF thread was falling behind, and solved it. Brilliant work my good name.. you made me look like a hero - standing on the shoulder of giants!! May 23, 2017 at 7:28
  • Helped me too, look at this for more options- stackoverflow.com/a/13891724/4836581
    – Zvi Redler
    Sep 11, 2019 at 10:10
8

The line [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)] did the trick in my case:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int? SomeNumber { get; set; }
1
  • [DatabaseGenerated(DatabaseGeneratedOption.None)] This saved my life as the field which I had decorated as KEY was actually not a Primary key in database table and had put only as a work around for entity framework to not throw an exception for model without key. And also this field was nullable. So whenever I was trying to add new record to this table it was giving this error probably because it was expecting this field to be generated from the database table which obviously was not happening due to that field was not key in the table.
    – Mantra
    Dec 21, 2021 at 14:11
7

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'.

1
  • 1
    hah, you clued me into the fact that i deleted my hidden id field in ASP.NET MVC. Thanks @Paulo! :) Jun 14, 2012 at 2:40
7

I came across this issue on a table that was missing a primary key and had a DATETIME(2, 3) column (so the entity's "primary key" was a combination of all the columns)... When performing the insert the timestamp had a more precise time (2018-03-20 08:29:51.8319154) that was truncated to (2018-03-20 08:29:51.832) so the lookup on key fields fails.

5

Just make sure table and form both have primary key and edmx updated.

i found that any errors during update were usually because of: - No primary key in Table - No primary key in Edit view/form (e.g. @Html.HiddenFor(m=>m.Id)

5

I also had this error. There are some situations where the Entity may not be aware of the actual Database Context you are using or the Model may be different. For this, set: EntityState.Modified; to EntityState.Added;

To do this:

if (ModelState.IsValid)
{
context.Entry(yourModelReference).State = EntityState.Added;
context.SaveChanges();
}

This will ensure the Entity knows youre using or adding the State youre working with. At this point all the correct Model Values need to be set. Careful not to loose any changes that may have been made in the background.

Hope this helps.

1
5
  @Html.HiddenFor(model => model.RowVersion)

My rowversion was null, so had to add this to the view which solved my issue

1
  • Wasn't passing the RowVersion from the View to the edit Action, plus I forgot to do the model binding for RowVersion. At the time you are saving the object to db, you need the previous value of the RowVersion submit to the db along with the object for the concurrency check. You make silly mistakes when you need things faster!
    – Dhanuka777
    Jan 25, 2016 at 3:02
4
    public void Save(object entity)
    {
        using (var transaction = Connection.BeginTransaction())
        {
        try
                {
                    SaveChanges();
                    transaction.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Deleted || ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Modified)
                        this.Refresh(RefreshMode.StoreWins, entity);
                    else if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Added)
                        Detach(entity);
                    AcceptAllChanges(); 
                    transaction.Commit();
                }
        }
    }
1
  • Can you please clarify what 'this' is referring to here and what is ObjectStateManager? I'm trying this in our base repository class but getting errors
    – Naomi
    Apr 30, 2018 at 22:23
4

I had the same problem. In my case I was trying to update the primary key, which is not allowed.

4

I got this error sporadically when using an async method. Has not happened since I switched to a synchronous method.

Errors sporadically:

[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public async Task<IHttpActionResult> Delete(int id, int customerId)
{
    var file = new Models.File() { Id = id, CustomerId = customerId };
    db.Files.Attach(file);
    db.Files.Remove(file);

    await db.SaveChangesAsync();

    return Ok();
}

Works all the time:

[Authorize(Roles = "Admin")]
[HttpDelete]
[Route("file/{id}/{customerId}/")]
public IHttpActionResult Delete(int id, int customerId)
{
    var file = new Models.File() { Id = id, CustomerId = customerId };
    db.Files.Attach(file);
    db.Files.Remove(file);

    db.SaveChanges();

    return Ok();
}
1
  • Although this resolved my issue, it served to point to the underlying issue mentioned earlier in this post about PKs & Row versions. I had neglected to add a schema map for a new table that was further complicated by the fact the PK did not follow the naming convention rule. <Table Name>ID. May 12, 2018 at 23:40
3

I got that error when I was deleting some rows in the DB (in the loop), and the adding the new ones in the same table.

The solutions for me was, to dynamicaly create a new context in each loop iteration

1
  • I had to do the same thing, still not sure why the problem occurred in the first place, but this works.
    – Jed Grant
    Sep 20, 2014 at 2:17
3

This will also happen if you are trying to insert into a unique constraint situation, ie if you can only have one type of address per employer and you try to insert a second of that same type with the same employer, you will get the same problem.

OR

This could also happen if all of the object properties that were assigned to, they were assigned with the same values as they had before.

        using(var db = new MyContext())
        {
            var address = db.Addresses.FirstOrDefault(x => x.Id == Id);

            address.StreetAddress = StreetAddress; // if you are assigning   
            address.City = City;                   // all of the same values
            address.State = State;                 // as they are
            address.ZipCode = ZipCode;             // in the database    

            db.SaveChanges();           // Then this will throw that exception
        }
3

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.

2

I got this exception when attaching an object that didn't exist in the database. I had assumed the object was loaded from a separate context, but if it was the user's first time visiting the site, the object was created from scratch. We have auto-incrementing primary keys, so I could replace

context.Users.Attach(orderer);

with

if (orderer.Id > 0) {
    context.Users.Attach(orderer);
}
2

Well i have this same issue. But this was due to my own mistake. Actually i was saving an object instead of adding it. So this was the conflict.

2

One way to debug this problem in an Sql Server environment is to use the Sql Profiler included with your copy of SqlServer, or if using the Express version get a copy of Express Profiler for free off from CodePlex by the following the link below:

Express Profiler

By using Sql Profiler you can get access to whatever is being sent by EF to the DB. In my case this amounted to:

exec sp_executesql N'UPDATE [dbo].[Category]
SET [ParentID] = @0, [1048] = NULL, [1033] = @1, [MemberID] = @2, [AddedOn] = @3
WHERE ([CategoryID] = @4)
',N'@0 uniqueidentifier,@1 nvarchar(50),@2 uniqueidentifier,@3 datetime2(7),@4 uniqueidentifier',
@0='E060F2CA-433A-46A7-86BD-80CD165F5023',@1=N'I-Like-Noodles-Do-You',@2='EEDF2C83-2123-4B1C-BF8D-BE2D2FA26D09',
@3='2014-01-29 15:30:27.0435565',@4='3410FD1E-1C76-4D71-B08E-73849838F778'
go

I copy pasted this into a query window in Sql Server and executed it. Sure enough, although it ran, 0 records were affected by this query hence the error being returned by EF.

In my case the problem was caused by the CategoryID.

There was no CategoryID identified by the ID EF sent to the database hence 0 records being affected.

This was not EF's fault though but rather a buggy null coalescing "??" statement up in a View Controller that was sending nonsense down to data tier.

2

None of the above answers quite covered my situation and the solution to it.

Code where the error was thrown in MVC5 controller:

        if (ModelState.IsValid)
        {
            db.Entry(object).State = EntityState.Modified; 
            db.SaveChanges(); // line that threw exception
            return RedirectToAction("Index");
        }

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).

2

This happened to me due to a mismatch between datetime and datetime2. Strangely, it worked fine prior to a tester discovering the issue. My Code First model included a DateTime as part of the primary key:

[Key, Column(Order = 2)]  
public DateTime PurchasedDate { get; set; } = (DateTime)SqlDateTime.MinValue;

The generated column is a datetime column. When calling SaveChanges, EF generated the following SQL:

-- Region Parameters
DECLARE @0 Int = 2
DECLARE @1 Int = 25
DECLARE @2 Int = 141051
DECLARE @3 DateTime2 = '2017-07-27 15:16:09.2630000' --(will not equal a datetime value)
-- EndRegion
UPDATE [dbo].[OrganizationSurvey]
SET [OrganizationSurveyStatusId] = @0
WHERE ((([SurveyID] = @1) AND ([OrganizationID] = @2)) AND ([PurchasedDate] = @3))

Because it was trying to match a datetime column with a datetime2 value, it returned no results. The only solution I could think of was to change the column to a datetime2:

[Key, Column(Order = 2, TypeName = "DateTime2")]  
public DateTime PurchasedDate { get; set; } = (DateTime)SqlDateTime.MinValue;
2
  • 1
    The strangeness of it working vs. not working has to do with the underlying format/base of datetime vs. datetime2. Essentially some millisecond values will evaluate to a match, others will not. The same thing happened to me and I also switched to DateTime2.
    – xr280xr
    Apr 24, 2018 at 20:57
  • +1 I wish I could +100 on this one for you. I after perusing around many places I finally found this and realized that, indeed, I had a Datetime as part of my primary key. Yes, this indeed fixed it. I updated the column to Datetime2 and it worked. Now, my beef is with Entity Framework for devising such a crappy query for this which forces me to do this.
    – Catchops
    May 22, 2019 at 21:32
1

If you are trying to create mapping in your edmx file to a "function Imports", this can result this error. Just clear the fields for insert, update and delete that is located in Mapping Details for a given entity in your edmx, and it should work. I hope I made it clear.

Not the answer you're looking for? Browse other questions tagged or ask your own question.