无法在Entity Framework中捕获SqlException异常

6

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

为什么你不试着捕获DBUpdateException异常呢? - DavidG
1
它会抛出什么异常?看一下“InnerException”,那可能就是你要找的。 - Arian Motamedi
@DavidG ه½“وˆ‘هœ¨ن¹‹هگژوچ•èژ·DbUpdateExceptionو—¶ï¼Œه®ƒن»چ然و— و³•وچ•èژ·هœ¨DbUpdateExceptionن¹‹ه‰چوٹ›ه‡؛çڑ„SqlExceptionم€‚ - Hello It's me
请检查我的答案,其中包含可直接使用的实用程序方法:https://dev59.com/hXfZa4cB1Zd3GeqPQFPZ#34670770 - yǝsʞǝla
2个回答

8
捕捉 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;
    }                
}

它抛出了 SqlException 还是 DbUpdateException?你检查了有多少个错误吗?你检查了第一个错误的错误编号吗? - aquinas
它会抛出两个异常,一个是 SqlException 和一个是 DbUpdateException,其中包括来自类型为 SqlException 的 InnerException。这两个 SqlExceptions 都具有错误编号 547。实际上,第一个 SqlException 似乎是无法捕获的,因为它不是由 SaveChanges() 引起的,而是由 System.Data.dll 引起的。 - Hello It's me

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接