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)
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.
.NET MVP 2002-2009
Chief Architect, MM .NET Application Framework