EF to MySql一般都是用using最後Commit,一直以為最後沒Commit,當using調用Dispose會自動Rollback,沒想到這兒有個坑,mysql有個bug並不會Rollback,事務也不會關閉,所以再次BeginTransaction就會報An error occurred ...
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