无法在Entity Framework中捕获SqlException

我想在删除实体时捕获外键exception。 但EF只会抛出自定义exception。 我需要检查是否存在外键违规,而不通过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。 试试这个:

 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.UpdateExceptionexception类型捕获唯一键冲突 ,没有尝试使用外键冲突。 我认为你也可以抓到外键违规。