2017-03-01 41 views
0

在我的一个WPF应用程序中,我正在全局级别处理我的异常。我使用下面的代码来处理异常。无法使用EntityCommandExecutionException找到数据库名称

private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) 
    { 
     if (e.Exception is System.Data.Entity.Core.EntityCommandExecutionException) 
     { 
      var entityException = e.Exception as System.Data.Entity.Core.EntityCommandExecutionException; 
      if (entityException.HResult == -2146232004) // Schema is different than expected 
      { 
       MessageBox.Show("Database exists but schema is different"); 
       e.Handled = true; 
      } 
     } 
    } 

它工作正常。但我使用具有不同连接字符串的多个DbContext,我想在错误中显示数据库的名称。我在EntityCommandExecutionException中找不到连接字符串。如何获取数据库名称?

回答

0

假设您的错误处理程序中的某个位置可以访问发生错误的DbContext对象,那么您可以使用dbContextObject.Database.Connection属性来获取SqlConnection对象,该对象提供有关数据库连接的各种属性包括数据库的名称。

+0

我在寻找那个“某处”。我在异常处理程序中找不到dbContext。 –

+0

啊。对 - 这个问题并不清楚。一个简单的方法可能是在引发异常的地方捕获异常,然后引发自定义异常,您可以将适当的DbContext对象的引用放入异常数据中,并将原始异常存储到内部异常中。 – SpaceUser7448