一种快速有效的方法来获得所需的内部异常

A fast and efficient way to get the needed Inner Exception

在使用 Entity Framework 6 的应用程序中,我在一个专门设计的实体中跟踪数据库中 table 所做的更改。他们跟踪所有 table 的变化,包括他们自己的 table。

所以如果在数据库中保存更改时发生异常,我删除所有挂起的跟踪实体以避免递归地创建新的和新的跟踪器,记录异常并退出保存方法。

但是,如果异常是由于连接超时引起的,我尝试3次重新保存更改,同时更改跟踪实体的EntityState以避免创建不必要的跟踪器。为了实现这一点,我需要捕获 DbUpdateException,在异常层次结构中获取 SqlException,并检查它的编号。但是,我不确定层次结构中的 SqlException 有多深。为了成功获得 Sql 异常,我这样写:

catch (DbUpdateException duEx)
{
   var inner = new Exception();
   inner = duEx;
   do
   {
      inner = inner.InnerException;
   }
   while (!(inner is SqlException) && inner != null);

   var innerEx = inner as SqlException;

   if (innerEx != null && innerEx.Number == -2)
   {
      //do job here
   }

我测试了它,它似乎可以工作,但它看起来有点笨拙。所以我的问题是:有没有办法直接获得 SqlException(如果有)?

What I was wondering is whether there is already some 3rd party extension method which I could use

没有,但您可以自己创建:

public static class Helper
{
    public static TException GetInnerException<TException>(this Exception ex) where TException : Exception
    {
         return ex.InnerException != null 
             ? ex.InnerException as TException ?? GetInnerException<TException>(ex.InnerException)
             : null;
    }
}

并使用它:

catch (DbUpdateException duEx)
{
   if (duEx.GetInnerException<SqlException>()?.Number == -2)
   {
      //do job here
   }
}