c# - 获取导致异常的查询

标签 c# mysql entity-framework

我正在创建一个应用程序,在数据库没有数据的情况下自动更新数据库结构。我们将其命名为UpdateApp。该应用程序由另一个使用 EntityFramework 访问 MySql 服务器的应用程序调用。该应用程序是MainApp。因为执行更新过程需要很长时间,所以主要思想是当MainApp中发生错误(例如没有表或没有定义字段......)时调用更新结构。

然后,我想确保我的 UpdateApp 已成功更新数据库。因此,我希望在更新并再次运行之前有导致 MainApp 中出现错误的查询。我尝试运行调试来查找异常对象中是否有任何字段包含查询,但仍然找不到任何内容。

try {
    using (DbContext ctx = ContextManager.CreateContext()) {
        // Do something, for example, get value from database
    }
} catch (EntityException ex) {
    if (ex.InnerException is MySqlException) {
        // 1. Handle update structure, call the UpdateApp here
        // 2. Try to get the query and run it again <= I get stuck here
    }
}

最佳答案

假设 MySqlException 的工作方式与 SqlException 相同,您无法通过异常访问 SqlCommand。但您肯定应该做的是重新运行整个失败的操作吗?像这样:

using (DbContext ctx = ContextManager.CreateContext())
{
   try
   {
      DoSomethingForExampleGetValueFromDatabase(DbContext ctx)
   }
   catch (EntityException ex)
   {
       if (ex.InnerException is MySqlException) 
       {
           // 1. Handle update structure, call the UpdateApp here
           DoSomethingForExampleGetValueFromDatabase(DbContext ctx)
       }
   }
}

private method DoSomethingForExampleGetValueFromDatabase(DbContext ctx)
{
}

引用文献:

Obtain the Query/CommandText that caused a SQLException

关于c# - 获取导致异常的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20397927/

相关文章:

c# - INSERT INTO 如果不存在 SQL Server

MySQL:选择已完成行的订单

java - MySQL 不会在搜索查询中同时返回波斯语和英语数字

entity-framework - 从存储库而不是 EF 实体返回 POCO 对象的优缺点是什么?

.net - 使用 Entity Framework Core 的分片策略

c# - Entity Framework 引用不自动加载

c# - 类内枚举的命名问题

C# 管理 UI 图形的更好方法

c# - WCF - 通过 HTTP 抛出客户端和服务绑定(bind)不匹配异常的二进制编码

php - Android中通过PHP和Mysql登录