title: Implementing retry logic for deadlock exceptions
body: <p>I've implemented a generic repository and was wondering if there is a smart way to implement a retry logic in case of a deadlock exception?</p>
  
  <p>The approach should be the same for all repository methods. So is there anyway I can avoid writing 'try/catch - call method again with retry-count', in every single method?</p>
  
  <p>Any suggetsion are welcome.</p>
  
  <p>A bit of my Repository code:</p>
  
  <pre><code>public class GenericRepository : IRepository
  {
      private ObjectContext _context;
  
      public List&lt;TEntity&gt; ExecuteStoreQuery&lt;TEntity&gt;(string commandText, params object[] parameters) where TEntity : class
      {
          List&lt;TEntity&gt; myList = new List&lt;TEntity&gt;();
  
          var groupData = _context.ExecuteStoreQuery&lt;TEntity&gt;(commandText, parameters);
  
          return myList;
      }
  
  
      public IQueryable&lt;TEntity&gt; GetQuery&lt;TEntity&gt;() where TEntity : class
      {          
          var entityName = GetEntityName&lt;TEntity&gt;();
          return _context.CreateQuery&lt;TEntity&gt;(entityName);
      }
  
      public IEnumerable&lt;TEntity&gt; GetAll&lt;TEntity&gt;() where TEntity : class
      {
          return GetQuery&lt;TEntity&gt;().AsEnumerable();
      }
  </code></pre>
  
  <p>EDIT: </p>
  
  <p><strong>1.Solution:</strong> </p>
  
  <p><em>Modified slightly from</em> <strong>chris.house.00</strong>'s <em>solution</em></p>
  
  <pre><code> public static T DeadlockRetryHelper&lt;T&gt;(Func&lt;T&gt; repositoryMethod, int maxRetries)
      {
          var retryCount = 0;
  
          while (retryCount &lt; maxRetries)
          {
              try
              {
                  return repositoryMethod();
              }
              catch (System.Data.SqlClient.SqlException ex)
              {
                  if (ex.Number == 1205)// Deadlock                         
                      retryCount++;
                  else
                      throw;                   
              }
          }
          return default(T);
      }
  </code></pre>
  
  <p>And you call it like this:</p>
  
  <pre><code>    public TEntity FirstOrDefault&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate) where TEntity : class
      {
          return RetryUtility.DeadlockRetryHelper&lt;TEntity&gt;( () =&gt;p_FirstOrDefault&lt;TEntity&gt;(predicate), 3);
      }
  
      protected TEntity p_FirstOrDefault&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate) where TEntity : class
      {
          return GetQuery&lt;TEntity&gt;().FirstOrDefault&lt;TEntity&gt;(predicate);
      }
  </code></pre>