【问题标题】:ASP MVC 4 MySQL, trouble handling transaction errorASP MVC 4 MySQL,处理事务错误的麻烦
【发布时间】:2013-11-30 22:49:17
【问题描述】:

我的环境/应用程序:Ubuntu(x64) Mono xsp4 mysql(strict_all_tables on) ASP.NET MVC4 Elmah

我正在尝试使用 ADO.NET 并将我的请求包装在事务中。我有一个表,其中一列是数据类型整数。我尝试插入 2 个整数,然后插入一个无效的数据类型。我的目标是让事务在尝试插入无效数据时回滚。 mysql 服务器在尝试从 MySQL Workbench 执行 sql 命令时抛出错误。

我在提交、回滚和关闭代码行上设置了断点。提交线被击中,十点关闭线被击中。但是服务器确实返回了 500 错误(YSOD)和 sql 异常,但我的异常处理没有捕获错误并回滚事务。

public class BaseController : Controller
{
    private MySqlConnection _connection;
    private MySqlTransaction _transaction;

    protected override void OnActionExecuting (ActionExecutingContext filterContext)
    {
        _connection = new MySqlConnection (ConfigurationManager.ConnectionStrings["myconnstringname"].ConnectionString);
        _connection.Open ();
        _transaction = _connection.BeginTransaction ();

        base.OnActionExecuting (filterContext);
    }

    protected override void OnActionExecuted (ActionExecutedContext filterContext)
    {
        try
        {
            _transaction.Commit ();
        }
        catch(Exception ex)
        {
            _transaction.Rollback();
            throw ex;
        }
        finally
        {
            _connection.Close ();
        }

        base.OnActionExecuted (filterContext);
    }

    protected MySqlCommand GetCommand(string commandText)
    {
        return new MySqlCommand (commandText, _connection, _transaction);
    }
}

public class HomeController : BaseController
{
    public ActionResult Index ()
    {
        var cmd = GetCommand ("insert into testing select 1;");
        cmd.ExecuteNonQuery ();

        cmd = GetCommand ("insert into testing select 2;");
        cmd.ExecuteNonQuery ();

        cmd = GetCommand ("insert into testing select 'grgregre';");
        cmd.ExecuteNonQuery ();

        return Content ("");
    }
}

【问题讨论】:

  • 删除throw ex 行?

标签: c# mysql asp.net asp.net-mvc-4 mono


【解决方案1】:

找出问题所在。我把这个弄坏了。显然异常被抛出在 cmd.ExecuteNonQuery();而不是事务提交的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2012-10-04
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多