Understanding the Entity Framework ConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows…

When working with the Entity Framework in n-Tier applications where you are unattaching and attaching entities from an object context, you may encounter this exception:


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.


This exception is letting you know that no rows were updated. There are several reasons why you may encounter this error.


One simple reason is that when attaching entities to an Object Context, you need to use the AddObject() method if the entity is newly created (and doesn’t have an Entity Key), whereas you can use the Object Context Attach() method if the entity already exists and is being updated. Here is some code to demonstrate this (where “EntityContainerName” is the name of your Entity Framework container and “EntitySetName” is the name of the Entity Set to which you are adding the entity):


if (entity.EntityKey == null || entity.EntityKey.IsTemporary)
{
   this.ObjectContext.AddObject(“EntityContainerName.EntitySetName”, entity);
}
else
{
   this.ObjectContext.Attach(entity);
}


Note that you need to be careful when adding entities that are related to other entity objects because Object Services attempts to add the related objects too.


Best Regards,
Kevin McNeish
.NET MVP 2002-2009
Chief Architect, MM .NET Application Framework
INETA Speaker
www.oakleafsd.com

2 thoughts on “Understanding the Entity Framework ConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows…”

  1. I am getting this error when performing an insert on our QA database, but cannot produce it in our development environment. The databases are identical. I know this is rather vague but I can provide you with code if necessary.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>