[英]Entity Framework Core - transaction cannot be roll back after commit
[英]Using a transaction to Roll Back Changes with the Entity Framework
我有一個特定的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;。
更改在代碼中。 謝謝
您需要完成交易,否則交易將被回滾。 因此,在您的代碼中,您需要添加Transaction.Complete()方法,如果不這樣做,它將自身回滾。
盡管您將此標記為已解決,但仍然是一個答案。
如果使用Entity Framework,則不必擔心事務。 上下文管理工作單元,並確保它在一個事務中已提交(或回滾)。 您的代碼包含過多的低級數據訪問內容。 讓EF做您的CRUD動作。
實體框架使您可以在代碼的大部分部分中保持持久性 。 我的意見是:您不需要DAO模式。 更糟糕的是:它只會阻礙您的前進。 它首先將數據庫操作和上下文實例分開,然后必須通過事務作用域將它們放在一起。 這意味着:您正在管理工作單元。 與POCO一起使用,而不與DAO一起使用。 讓一個上下文實例跟蹤更改並通過一個SaveChanges()
調用將其保存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.