qak*_*mak 9 c# mysql entity-framework entity-framework-5 visual-studio-2012
我想同时转换一些表.如果一个人不成功,必须全部回滚.
像这样的东西:
ctx.Database.ExecuteSqlCommand("truncate table tb_expensesall");
ctx.Database.ExecuteSqlCommand("truncate table tb_wholesale");
ctx.Database.ExecuteSqlCommand("truncate table tb_singlesale");
ctx.Database.ExecuteSqlCommand("truncate table tb_purchase");
Run Code Online (Sandbox Code Playgroud)
但问题是,我不知道如何使用交易.
我试着这个:
using (gasstationEntities ctx = new gasstationEntities(Resources.CONS))
{
ctx.Database.Connection.Open();
DbTransaction tr = ctx.Database.Connection.BeginTransaction();
try
{
ctx.Database.ExecuteSqlCommand("truncate table tb_expensesall");
ctx.Database.ExecuteSqlCommand("truncate table tb_wholesale");
ctx.Database.ExecuteSqlCommand("truncate table tb_singlesale");
ctx.Database.ExecuteSqlCommand("truncate table tb_purchase");
//commit the transaction
tr.Commit();
new MessageWindow(this, Resources.GetString("Warn"), Resources.GetString("DeleteSuccess"));
}
catch (Exception ex)
{
//return
tr.Rollback();
}
//close
ctx.Database.Connection.Close();
}
Run Code Online (Sandbox Code Playgroud)
这里的问题: tr.Commit();
和Exception告诉我:
{System.InvalidOperationException: Connection must be valid and open to rollback transaction
Run Code Online (Sandbox Code Playgroud)
而tr.Rollback();抛出异常.例外是:
{System.InvalidOperationException: Connection must be valid and open to rollback transaction
Run Code Online (Sandbox Code Playgroud)
真正有趣的是,表截断是成功的.什么?提交是抛出异常.它可以成功吗?我无法理解.
请告诉我什么是goning.如果你给我一个解决方案,那就更好了.
JYL*_*JYL 21
尝试封装您的代码
using (gasstationEntities ctx = new gasstationEntities(Resources.CONS))
{
using (var scope = new TransactionScope())
{
[... your code...]
scope.Complete();
}
}
Run Code Online (Sandbox Code Playgroud)
如果发生异常,则不会调用scope.Complete()并且回滚是自动的.
编辑:我刚看到你的MySql标签.如果这不起作用,请看看这里!