【发布时间】:2012-11-06 08:10:37
【问题描述】:
我有这个从通用 DAO 继承方法的特定 DAO 我想在此代码中添加一个事务,以便在发现异常时回滚所有更改
TDAO tDAO = new TDAO();
TDAO2 tDAO2 = new TDAO2();
//Get the DAO to delete from the database let's call them dDao and dDao2
//Start the Transaction
using (TransactionScope trans = new TransactionScope())
{
try
{
//Delete all SGC Associated switch
TDAO2.Delete(dDao);
//Delete switch
TDAO.Delete(dDao2);
//send notification
base.SendChangeNotification();
//Commit the Information Completing the Transaction
trans.Complete();
}
catch (UpdateException ex)//SQL exception
{
//Log the error
//Rollback the changes if there is an exception
throw new Exception(Resources.ErrorMessages.OperationNotPermited);
}
catch (Exception ex) //Other exception
{
//Log the error
throw new Exception(Resources.ErrorMessages.UndifenedError);
}
}
在 Visual Studio 中,转到项目中的“引用”图标。右键单击,添加引用。然后搜索 System.Transactions.dll。选择它,单击确定。然后尝试重建您的项目。还要确保顶部有 Using 语句 (C#) 或 Imports 语句 (VB),例如 Using System.Transactions;
并且更改在代码中。谢谢你
【问题讨论】:
-
你想回滚什么?更改数据库?或更改数据上下文?对于数据库的更改 - 只需使用常规数据库事务。对于数据上下文的更改 - 不要:将其丢弃。
-
我想回滚对 DB 的更改。我该怎么做?
-
哦,只是为了补充信息,数据库管理系统是 SQL Server 2008
-
我认为最好留下原始问题并将您的解决方案添加为下面的答案。然后接受你的回答是正确的。它将问题标记为已回答,其他用户将看到问题和解决方案。
-
用户,您以错误的方式使用 StackOverflow。问题应保持为问题,答案应作为答案提供。
标签: c# entity-framework-4 transactions dao data-access