在实体框架中无法捕获SqlException [英] Cannot catch SqlException in Entity Framework

查看:91
本文介绍了在实体框架中无法捕获SqlException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在删除实体时捕获外键异常。但是EF仅引发自定义异常。我需要检查是否存在外键冲突,而无需通过EF手动检查所有关系。

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


推荐答案

捕获DbUpdateException。尝试以下操作:

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

这篇关于在实体框架中无法捕获SqlException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆