无法在Entity Framework中捕获SqlException

时间:2014-09-19 14:46:15

标签: c# entity-framework

我想在删除实体时捕获外键异常。但EF只会抛出自定义异常。我需要检查是否存在外键违规而不检查所有关系"手动"通过EF。

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 > 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;      
       }
    }
}

2 个答案:

答案 0 :(得分:4)

Catch DbUpdateException。试试这个:

try 
{
    applicationDbContext.SaveChanges();
    return RedirectToAction("Index");
}
catch (DbUpdateException e) {
    var sqlException = e.GetBaseException() as SqlException;
    if (sqlException != null) {
        if (sqlException .Errors.Count > 0) {
            switch (sqlException .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;      
            }
        }
    }
    else {
       throw;
    }                
}

答案 1 :(得分:0)

我能够使用 System.Data.UpdateException 异常类型捕获唯一键冲突,没有尝试使用外键冲突。我认为你也可以抓到外键违规。