title: Retry Entity Framwork DbContext.SaveChanges after double inserting a key
body: <p>I am using Entity Framework on Azure. After makes a few changes to my data I call the <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.savechanges%28v=vs.113%29.aspx" rel="nofollow"><code>DbContext.SaveChanges</code> </a>.</p>
  
  <p>In my code, <code>Messages</code> belong to <code>Conversations</code>. On receiving a message I add it to the Messages table and create its parent in the Conversations table. If I get two messages come in at once with the same parent, there is a possibility of double inserting values with the same primary key into the Conversations table.</p>
  
  <p><strong>The process:</strong></p>
  
  <p>I'll call some "insert conversation if it doesn't exist code":</p>
  
  <pre><code> if (this.Context.Conversations.SingleOrDefault(fc =&gt; fc.ConversationId == conversation.ConversationId) == null)
          {
              Context.Entry(conversation).State = EntityState.Added; //public DbEntityEntry Entry(object entity);
          }
  </code></pre>
  
  <p>Later on I'll  call <code>this.Context.SaveChanges</code></p>
  
  <hr>
  
  <p>I've been reading <a href="http://blogs.msdn.com/b/appfabriccat/archive/2010/12/11/sql-azure-and-entity-framework-connection-fault-handling.aspx" rel="nofollow">SQL Azure and Entity Framework Connection Fault Handling</a> and I'm pretty sure I want to implement a Retry Policy With Transaction Scope.</p>
  
  <ul>
  <li><p><strong>How do I go about wrapping <code>SaveChanges</code> in a retry policy</strong>
  Some thoughts: How do I go about wrapping <code>SaveChanges</code> in a retry policy. Will this retry the code I ran earlier that checked if the conversation existed? How do I make my retry policy retry for non-transient faults (like PK violations)?</p></li>
  <li><p>If a retry policy isn't possible , what is the entity framework approach to burying the "create or edit if exists" logic as far down as possible when saving a context? Is it best to just call a stored procedure in this special case?</p></li>
  </ul>