標籤:asp.net 分散式交易
最近在做項目的時候遇到分散式交易,所有總結一下,跟大家分享和交流一下經驗。首先說明為什麼要分散式交易呢?先說說我在項目的哪裡遇到分散式交易吧,我是在做網站後台開發的時候,一般涉及到有圖片表的設計時,資料庫存放的是圖片的路徑,圖片是存放在網站的檔案夾下面,所以我們操作產品表時,當我要刪除資料庫產品圖片路徑,同時要把存在網站目錄下的圖片也刪掉,為了實現這功能,我就使用了分散式交易。
思路:
1、在項目中必須引用 System.Transactions 程式集
2、在需要進行事務管控的代碼方法:System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope()
3、必須啟動服務 Distributed Transaction Coordinator才能進行分散式交易的正常運行
下面是我寫的一個例子主要代碼:
//根據id將資料庫和檔案夾的圖片一起刪掉 //根據id得到實體物件 ProductEntity entity = Product_BLLSub.Get_ProductEntity(int.Parse(id)); //建立一個事務 using (System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope()) { //刪除資料庫圖片的資料 Product_BLLSub.Create_ProductDelete(int.Parse(id)); //得到圖片的路徑 string thumphyPath = context.Server.MapPath("/upload/thum/") + entity.img_url; string imgPhyPath = context.Server.MapPath("/upload/img/") + entity.img_url; //刪除縮圖 if (System.IO.File.Exists(thumphyPath)) { System.IO.File.Delete(thumphyPath); } //刪除原圖 if (System.IO.File.Exists(imgPhyPath)) { System.IO.File.Delete(imgPhyPath); } //提交事務 scop.Complete(); } //刪除成功 Response.Write("刪除成功");
說明:我操作資料庫的方法是將資料庫資料取出來轉換成實體物件,然後通過操作實體物件來操作資料庫。
本文出自 “靈雨飄零部落格” 部落格,請務必保留此出處http://101779.blog.51cto.com/91779/1547382
ASP.NET中分散式交易的使用