title: Entity Framework 4.2 : Getting proper database errors
body: <p>In my ASP.NET MVC 3 application, I use EF 4.2. In my database, I have a unique constraint for a column. </p>
  
  <p>I try to insert same data in order to see what I get but I am getting the below error:</p>
  
  <blockquote>
    <p>An error occurred while updating the entries. See the inner exception
    for details.</p>
  </blockquote>
  
  <p>Inside the inner exception I can see the full error about unique constraint. But how can I uniquely catch this exception to tell the user this:</p>
  
  <blockquote>
    <p>You are entering the same value again.</p>
  </blockquote>
  
  <p>Here is what I do currently:</p>
  
  <pre><code>try
  {
      UpdateModel&lt;ConditionType&gt;(conditionType, null, null, new string[] { "ConditionTypeId" });
      _conditionTypeRepository.Save();
  
      return RedirectToAction("conditiontype");
  }
  catch (Exception ex)
  {
      ModelState.AddModelError("", "There was an error while updating: " + ex.Message);
  }
  </code></pre>
  
  <p>But this is a generic approach. What I would like to do is to provide a specific message.</p>
  
  <p>Any thoughts?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>I tired the below but this time it didn't catch it:</p>
  
  <pre><code>catch (SqlException ex)
  {
      if (ex.Number == 2627)
      {
          ModelState.AddModelError("", "You are entering the same value again.");
      }
  
      ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
  }
  </code></pre>
  
  <p>I dug into a little bit and it turned out that it throws an exception type of <code>System.Data.Entity.Infrastructure.DbUpdateException</code> which does not contain the exception number.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Here how I solve the problem but I am sure it is not the best way of solving it. Any idea how to refactor this code?</p>
  
  <pre><code>catch (Exception ex) {
  
      if (ex.InnerException.InnerException.GetType() == typeof(SqlException)) {
  
          if (((SqlException)ex.InnerException.InnerException).Number == 2627)
              ModelState.AddModelError("", "You are entering the same value again.");
          else
              ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
  
      } else {
          ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
      }
  }
  </code></pre>