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.
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;
}
}
}
Catch DbUpdateException. Try this:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With