最近在使用.Net中的TransactionScope事务的过程中,发现个问题,当事务提交后
直接return到另一个控制器来执行数据库操作,结果数据库连接不能使用,
后来发现原来是return语句不应该放在事务中,只有当事务提交后才真正的释放连接,否则再次打开
只不过是提交事务而已,因此需要在事务using范围外执行再次的数据库操作
错误代码:
//如果没有改变分类
if (theModuleId == moduleId)
{
return this.SavePublishInfo(identifier, infoTitle, moduleId, linkManId, infoContent, picture, keyWords,displayLinkMan);
}
else//如果修改了分类,先插入到新分类表中一条记录,然后删除源记录
{
using (System.Transactions.TransactionScope tx = new System.Transactions.TransactionScope())
{
//先插入一条记录
int userid = ((UserInfo)Session["User"]).Identifier;
Information information = new Information();
try
{
business.Save<Information>(information);
try
{
//然后再按id和moduleID删除原记录
//Information info = new Information();
information.Identifier = identifier;
information.ModuleId = theModuleId;
business.Remove<Information>(information);
tx.Complete();
return this.Index();
}
catch (Exception e)
{
//回滚事务
tx.Dispose();
return baseController.Error("Error", "错误提示", "修改记录失败!错误信息:</br>" + e.Message);
}
}
catch (Exception e)
{
tx.Dispose();
return baseController.Error("Error", "错误提示", "修改记录失败!错误信息:</br>" + e.Message);
}
}
正确代码:
注意:return this.Index();
//如果没有改变分类
if (theModuleId == moduleId)
{
return this.SavePublishInfo(identifier, infoTitle, moduleId, linkManId, infoContent, picture, keyWords,displayLinkMan);
}
else//如果修改了分类,先插入到新分类表中一条记录,然后删除源记录
{
using (System.Transactions.TransactionScope tx = new System.Transactions.TransactionScope())
{
//先插入一条记录
int userid = ((UserInfo)Session["User"]).Identifier;
Information information = new Information();
try
{
business.Save<Information>(information);
try
{
//然后再按id和moduleID删除原记录
//Information info = new Information();
information.Identifier = identifier;
information.ModuleId = theModuleId;
business.Remove<Information>(information);
tx.Complete();
}
catch (Exception e)
{
//回滚事务
tx.Dispose();
return baseController.Error("Error", "错误提示", "修改记录失败!错误信息:</br>" + e.Message);
}
}
catch (Exception e)
{
tx.Dispose();
return baseController.Error("Error", "错误提示", "修改记录失败!错误信息:</br>" + e.Message);
}
}
return this.Index();
Mikel