title: How can I catch UniqueKey Violation exceptions with EF6 and SQL Server?
body: <p>One of my tables have a unique key and when I try to insert a duplicate record it throws an exception as expected. But I need to distinguish unique key exceptions from others, so that I can customize the error message for unique key constraint violations.</p>
  
  <p>All the solutions I've found online suggests to cast <code>ex.InnerException</code> to <code>System.Data.SqlClient.SqlException</code> and check the if <code>Number</code> property is equal to 2601 or 2627 as follows:</p>
  
  <pre><code>try
  {
      _context.SaveChanges();
  }
  catch (Exception ex)
  {
      var sqlException = ex.InnerException as System.Data.SqlClient.SqlException;
  
      if (sqlException.Number == 2601 || sqlException.Number == 2627)
      {
          ErrorMessage = "Cannot insert duplicate values.";
      }
      else
      {
          ErrorMessage = "Error while saving data.";
      }
  }
  </code></pre>
  
  <p>But the problem is, casting <code>ex.InnerException</code> to <code>System.Data.SqlClient.SqlException</code> causes invalid cast error since <code>ex.InnerException</code> is actually type of <code>System.Data.Entity.Core.UpdateException</code>, not <code>System.Data.SqlClient.SqlException</code>.</p>
  
  <p>What is the problem with the code above? How can I catch Unique Key Constraint violations?</p>