你的位置:首页 > ASP.net教程

[ASP.net教程]MySql EF事务using不会自动 Rollback的bug


    EF to MySql一般都是用using最后Commit,一直以为最后没Commit,当using调用Dispose会自动Rollback,没想到这儿有个坑,mysql有个bug并不会Rollback,事务也不会关闭,所以再次BeginTransaction就会报An error occurred while starting a transaction on the provider connection. See the inner exception for details.错误详情是Nested transactions are not supported.

  所以用 EF to MySql一定要记得try catch  Rollback

例子如下

      using (var db = new OtoRCEntities())      {        using (var tran = db.Database.BeginTransaction())        {          try          {            db.Database.ExecuteSqlCommand("update xxx");            tran.Commit();          }          catch (Exception)//这儿try catch 是用来报错了没有Commit,按理说using后应该自动Rollback          {                      }        }      }      using (var db = new OtoRCEntities())      {        using (var tran = db.Database.BeginTransaction())//到这儿就会报错        {          try          {            db.Database.ExecuteSqlCommand("update xxx");            tran.Commit();          }          catch (Exception)          {          }        }      }

 

  具体MySql bug地址: http://bugs.mysql.com/bug.php?id=71502