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.php

  因此用 EF to MySql必定要記得try catch  Rollbackmysql

例子以下sql

            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=71502ide

相關文章
相關標籤/搜索