title: Cannot catch SqlException in Entity Framework
body: <p>I want to catch a foreign key exception when deleting an entity. But EF only throws custom exceptions. I need to check if there is a foreign key violation without checking all the relations "manually" via the EF.</p>
  
  <pre><code>try 
  {
     applicationDbContext.SaveChanges();
     // even though debugger shows an SqlException at first, it doesnt get caught but an DBUpdateException is thrown...
     return RedirectToAction("Index");
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
     if (ex.Errors.Count &gt; 0) 
     {
        switch (ex.Errors[0].Number)
        {
           case 547: // Foreign Key violation
                    ModelState.AddModelError("CodeInUse", "Country code could not be deleted, because it is in use");
                    return View(viewModel.First());
           default:
                    throw;      
         }
      }
  }
  </code></pre>