title: How to solve this error of System.Data.Entity.Core.OptimisticConcurrencyException
body: <p>Exception type : </p>
  
  <blockquote>
    <p>System.DataEntity.Core.OptimisticConcurrencyException</p>
  </blockquote>
  
  <p>Message : </p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>Stack trace:</p>
  
  <blockquote>
    <p>System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRow>sAffected(Int64,
    System.Data.Entity.Core.Mapping.Update.Internal.UpdateCommand)<br>
    System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
        System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[[System.Int32,
    mscorlib]](System.Func1,
    System.Data.Entity.Infrastructure.IDbExecutionStrategy, Boolean,
    Boolean)<br>
    System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions,
    System.Data.Entity.Infrastructure.IDbExecutionStrategy, Boolean)<br>
    System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[System.Int32,
    mscorlib]<br>
    System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions,
    Boolean) 
        System.Data.Entity.Internal.InternalContext.SaveChanges()</p>
  </blockquote>
  
  <p><strong>Code 1) EfRepository:</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Data.Entity;
  using System.Data.Entity.Validation;
  using System.Linq;
  using Nop.Core;
  using Nop.Core.Data;
  namespace Nop.Data
  {
      /// &lt;summary&gt;
      /// Entity Framework repository
      /// &lt;/summary&gt;
      public partial class EfRepository&lt;T&gt; : IRepository&lt;T&gt; where T : BaseEntity
      {
          #region Fields
          private readonly IDbContext _context;
          private IDbSet&lt;T&gt; _entities;
          #endregion
          #region Ctor
          /// &lt;summary&gt;
          /// Ctor
          /// &lt;/summary&gt;
          /// &lt;param name="context"&gt;Object context&lt;/param&gt;
          public EfRepository(IDbContext context)
          {
              this._context = context;
          }
  
          #endregion 
          #region Methods
          /// &lt;summary&gt;
          /// Get entity by identifier
          /// &lt;/summary&gt;
          /// &lt;param name="id"&gt;Identifier&lt;/param&gt;
          /// &lt;returns&gt;Entity&lt;/returns&gt;
          public virtual T GetById(object id)
          {
              //see some suggested performance optimization (not tested)
              //http://stackoverflow.com/questions/11686225/dbset-find-method-ridiculously-slow-compared-to-singleordefault-on-id/11688189#comment34876113_11688189
              return this.Entities.Find(id);
          }
          /// &lt;summary&gt;
          /// Insert entity
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;Entity&lt;/param&gt;
          public virtual void Insert(T entity)
          {
              try
              {
                  if (entity == null)
                      throw new ArgumentNullException("entity");
  
                  this.Entities.Add(entity);
  
                  this._context.SaveChanges();
              }
              catch (DbEntityValidationException dbEx)
              {
                  var msg = string.Empty;
  
                  foreach (var validationErrors in dbEx.EntityValidationErrors)
                      foreach (var validationError in validationErrors.ValidationErrors)
                          msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
   var fail = new Exception(msg, dbEx);
                  //Debug.WriteLine(fail.Message, fail);
                  throw fail;
              }
          }
  
          /// &lt;summary&gt;
          /// Insert entities
          /// &lt;/summary&gt;
          /// &lt;param name="entities"&gt;Entities&lt;/param&gt;
          public virtual void Insert(IEnumerable&lt;T&gt; entities)
          {
              try
              {
                  if (entities == null)
                      throw new ArgumentNullException("entities");
  
                  foreach (var entity in entities)
                      this.Entities.Add(entity);
  
                  this._context.SaveChanges();
              }
              catch (DbEntityValidationException dbEx)
              {
                  var msg = string.Empty;
  
                  foreach (var validationErrors in dbEx.EntityValidationErrors)
                      foreach (var validationError in validationErrors.ValidationErrors)
                          msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
  
                  var fail = new Exception(msg, dbEx);
                  //Debug.WriteLine(fail.Message, fail);
                  throw fail;
              }
          }
  
          /// &lt;summary&gt;
          /// Update entity
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;Entity&lt;/param&gt;
          public virtual void Update(T entity)
          {
              try
              {
                  if (entity == null)
                      throw new ArgumentNullException("entity");
  
                  this._context.SaveChanges();
              }
              catch (DbEntityValidationException dbEx)
              {
                  var msg = string.Empty;
  
                  foreach (var validationErrors in dbEx.EntityValidationErrors)
                      foreach (var validationError in validationErrors.ValidationErrors)
                          msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
  
                  var fail = new Exception(msg, dbEx);
                  //Debug.WriteLine(fail.Message, fail);
                  throw fail;
              }
          }
  
          /// &lt;summary&gt;
          /// Delete entity
          /// &lt;/summary&gt;
          /// &lt;param name="entity"&gt;Entity&lt;/param&gt;
          public virtual void Delete(T entity)
          {
              try
              {
                  if (entity == null)
                      throw new ArgumentNullException("entity");
  
                  this.Entities.Remove(entity);
  
                  this._context.SaveChanges();
              }
              catch (DbEntityValidationException dbEx)
              {
                  var msg = string.Empty;
  
                  foreach (var validationErrors in dbEx.EntityValidationErrors)
                      foreach (var validationError in validationErrors.ValidationErrors)
                          msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
  
                  var fail = new Exception(msg, dbEx);
                  //Debug.WriteLine(fail.Message, fail);
                  throw fail;
              }
          }
  
          /// &lt;summary&gt;
          /// Delete entities
          /// &lt;/summary&gt;
          /// &lt;param name="entities"&gt;Entities&lt;/param&gt;
          public virtual void Delete(IEnumerable&lt;T&gt; entities)
          {
              try
              {
                  if (entities == null)
                      throw new ArgumentNullException("entities");
  
                  foreach (var entity in entities)
                      this.Entities.Remove(entity);
  
                  this._context.SaveChanges();
              }
              catch (DbEntityValidationException dbEx)
              {
                  var msg = string.Empty;
  
                  foreach (var validationErrors in dbEx.EntityValidationErrors)
                      foreach (var validationError in validationErrors.ValidationErrors)
                          msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
  
                  var fail = new Exception(msg, dbEx);
                  //Debug.WriteLine(fail.Message, fail);
                  throw fail;
              }
          }
  
          #endregion
  
          #region Properties
  
          /// &lt;summary&gt;
          /// Gets a table
          /// &lt;/summary&gt;
          public virtual IQueryable&lt;T&gt; Table
          {
              get
              {
                  return this.Entities;
              }
          }
  
          /// &lt;summary&gt;
          /// Gets a table with "no tracking" enabled (EF feature) Use it only when you load record(s) only for read-only operations
          /// &lt;/summary&gt;
          public virtual IQueryable&lt;T&gt; TableNoTracking
          {
              get
              {
                  return this.Entities.AsNoTracking();
              }
          }
  
          /// &lt;summary&gt;
          /// Entities
          /// &lt;/summary&gt;
          protected virtual IDbSet&lt;T&gt; Entities
          {
              get
              {
                  if (_entities == null)
                      _entities = _context.Set&lt;T&gt;();
                  return _entities;
              }
          }
  
          #endregion
      }
  }
  </code></pre>
  
  <p><strong>IDbContext</strong></p>
  
  <pre><code>using System.Collections.Generic;
  using System.Data.Entity;
  using Nop.Core;
  
  namespace Nop.Data
  {
      public interface IDbContext
      {
          /// &lt;summary&gt;
          /// Get DbSet
          /// &lt;/summary&gt;
          /// &lt;typeparam name="TEntity"&gt;Entity type&lt;/typeparam&gt;
          /// &lt;returns&gt;DbSet&lt;/returns&gt;
          IDbSet&lt;TEntity&gt; Set&lt;TEntity&gt;() where TEntity : BaseEntity;
  
          /// &lt;summary&gt;
          /// Save changes
          /// &lt;/summary&gt;
          /// &lt;returns&gt;&lt;/returns&gt;
          int SaveChanges();
  
          /// &lt;summary&gt;
          /// Execute stores procedure and load a list of entities at the end
          /// &lt;/summary&gt;
          /// &lt;typeparam name="TEntity"&gt;Entity type&lt;/typeparam&gt;
          /// &lt;param name="commandText"&gt;Command text&lt;/param&gt;
          /// &lt;param name="parameters"&gt;Parameters&lt;/param&gt;
          /// &lt;returns&gt;Entities&lt;/returns&gt;
          IList&lt;TEntity&gt; ExecuteStoredProcedureList&lt;TEntity&gt;(string commandText, params object[] parameters)
              where TEntity : BaseEntity, new();
  
          /// &lt;summary&gt;
          /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
          /// &lt;/summary&gt;
          /// &lt;typeparam name="TElement"&gt;The type of object returned by the query.&lt;/typeparam&gt;
          /// &lt;param name="sql"&gt;The SQL query string.&lt;/param&gt;
          /// &lt;param name="parameters"&gt;The parameters to apply to the SQL query string.&lt;/param&gt;
          /// &lt;returns&gt;Result&lt;/returns&gt;
          IEnumerable&lt;TElement&gt; SqlQuery&lt;TElement&gt;(string sql, params object[] parameters);
  
          /// &lt;summary&gt;
          /// Executes the given DDL/DML command against the database.
          /// &lt;/summary&gt;
          /// &lt;param name="sql"&gt;The command string&lt;/param&gt;
          /// &lt;param name="doNotEnsureTransaction"&gt;false - the transaction creation is not ensured; true - the transaction creation is ensured.&lt;/param&gt;
          /// &lt;param name="timeout"&gt;Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used&lt;/param&gt;
          /// &lt;param name="parameters"&gt;The parameters to apply to the command string.&lt;/param&gt;
          /// &lt;returns&gt;The result returned by the database after executing the command.&lt;/returns&gt;
          int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters);
      }
  }
  </code></pre>