title: How to fix OptimisticConcurrencyException in an MVC application
body: <p>We have an application that is giving the following error message (from time to time, not often):</p>
  
  <blockquote>
    <p>System.Data.Entity.Core.OptimisticConcurrencyException: 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>I looked at other answers and tried them (primary key id being zero), but I'm not able to reproduce.</p>
  
  <p>The code that saves records is implemented as a command invoker. The Execute method receives the command object to save, and calls the Handle method of the handler:</p>
  
  <pre><code>public class CommandInvoker : ICommandInvoker
  {
      private readonly IKernel _kernel;
      private readonly IArhomaContext _context;
  
      public CommandInvoker(IKernel kernel, IArhomaContext context)
      {
          _kernel = kernel;
          _context = context;
      }
  
      public void Execute&lt;T&gt;(T command)
      {
          var handler = _kernel.TryGet&lt;ICommandHandler&lt;T&gt;&gt;();
          handler.Handle(command);
          _context.SaveChanges();
      }
  }
  </code></pre>
  
  <p>Can someone guide me as to how we can fix this problem? Should we put the SaveChanges inside a try catch and catch an OptimisticConcurrencyException? I'm unable to reproduce it, but we get this in production.</p>