ASP.NET中分布式事务的使用

以前发表了一篇事务的存储过程,最近在作项目的时候遇到分布式事务,全部总结一下,跟你们分享和交流一下经验。首先说明为何要分布式事务呢?先说说我在项目的哪里遇到分布式事务吧,我是在作网站后台开发的时候,通常涉及到有图片表的设计时,数据库存放的是图片的路径,图片是存放在网站的文件夹下面,因此咱们操做产品表时,当我要删除数据库产品图片路径,同时要把存在网站目录下的图片也删掉,为了实现这功能,我就使用了分布式事务。数据库

思路:分布式

 一、在项目中必须引用 System.Transactions 程序集网站

 二、在须要进行事务管控的代码方法:System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope()url

 三、必须启动服务 Distributed Transaction Coordinator才能进行分布式事务的正常运行spa

下面是我写的一个例子主要代码:设计

 1          //3.根据id将数据库和文件夹的图片一块儿删掉
 2 
 3             //3.0根据id获得实体对象
 4             ProductEntity entity = Product_BLLSub.Get_ProductEntity(int.Parse(id));
 5            //3.1建立一个事务
 6             using (System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope())
 7             { 
 8                 //3.2删除数据库图片的数据
 9                  Product_BLLSub.Create_ProductDelete(int.Parse(id));
10               12                     //3.3获得图片的路径
13                     string thumphyPath = context.Server.MapPath("/upload/thum/") + entity.img_url;
14                     string imgPhyPath = context.Server.MapPath("/upload/img/") + entity.img_url;
15                     //3.4删除缩略图
16                     if (System.IO.File.Exists(thumphyPath))
17                     {
18                         System.IO.File.Delete(thumphyPath);
19                     }
20                     //3.5删除原图
21                     if (System.IO.File.Exists(imgPhyPath))
22                     {
23                         System.IO.File.Delete(imgPhyPath);
24                     }
25                     //3.6提交事务
26                     scop.Complete();
27                 }
28        35          //删除成功
36          Response.Write("删除成功");

说明:我操做数据库的方法是将数据库数据取出来转换成实体对象,而后经过操做实体对象来操做数据库。code

相关文章
相关标签/搜索