无法在实体框架中捕获SqlException

本文关键字:SqlException 框架 实体 | 更新日期: 2023-09-27 18:23:39

我想在删除实体时捕获外键异常。但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;      
       }
    }
}

无法在实体框架中捕获SqlException

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

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