zoukankan      html  css  js  c++  java
  • ASP.NET中分布式事务的使用

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

    思路:

     1、在项目中必须引用 System.Transactions 程序集

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

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

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

     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("删除成功");

    说明:我操作数据库的方法是将数据库数据取出来转换成实体对象,然后通过操作实体对象来操作数据库。

  • 相关阅读:
    [模板] 循环数组的最大子段和
    [最短路][几何][牛客] [国庆集训派对1]-L-New Game
    [洛谷] P1866 编号
    1115 Counting Nodes in a BST (30 分)
    1106 Lowest Price in Supply Chain (25 分)
    1094 The Largest Generation (25 分)
    1090 Highest Price in Supply Chain (25 分)
    树的遍历
    1086 Tree Traversals Again (25 分)
    1079 Total Sales of Supply Chain (25 分 树
  • 原文地址:https://www.cnblogs.com/xiaoyuanding/p/3947986.html
Copyright © 2011-2022 走看看