gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:23:53 25 4
gpt4 key购买 nike

我正在创建一个应用程序,在数据库没有数据的情况下自动更新数据库结构。我们将其命名为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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com