【转】 .NET开发中的事务处理大比拼 之 ASP.NET页面级别的事务

返回C#与Java社区
0回复贴,共1页,点击数:1367

ASP.NET事务可以说是在.NET平台上事务实现方式最简单的一种,你仅仅需要一行代码即可。在aspx的页面声明中加一个额外的属性,即事务属性Transaction="Required",它有如下的值:Disabled(默认)、NotSupportedSupportedRequiredRequiresNew,这些设置和COM+及企业级服务中的设置一样,典型的一个例子是如果你想在页面上下文中运行事务,那么要将其设置为Required。如果页面中包含有用户控件,那么这些控件也会包含到事务中,事务会存在于页面的每个地方。
        代码示例:
页面声明Transaction="Required"

<%@ Page Transaction="Required"  Language="C#" AutoEventWireup="true" 
CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication4.WebForm3" %>

页面引用:using System.EnterpriseServices;
然后,数据操作代码:

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        Work1();
        Work2();
        ContextUtil.SetComplete();   //提交事务
    }
    catch (System.Exception except)
    {
        ContextUtil.SetAbort();      //撤销事务
        Response.Write(except.Message);
    }  
}  
private void Work1()
{
    string conString = "data source=127.0.0.1;database=codematic;user id=sa;
      password=";
    SqlConnection myConnection = new SqlConnection(conString);
    string strSql = "Insert Into P_Category(CategoryId,Name)values('1',
      'test1')";
    SqlCommand myCommand = new SqlCommand(strSql, myConnection);
    myConnection.Open();
    int rows = myCommand.ExecuteNonQuery();
    myConnection.Close();
}
private void Work2()
{
    string conString = "data source=127.0.0.1;database=codematic;user id=sa;
      password=";
    SqlConnection myConnection = new SqlConnection(conString);
    string strSql = "Insert Into P_Category(CategoryId,Name)values('2',
      'test2')";
    SqlCommand myCommand = new SqlCommand(strSql, myConnection);
    myConnection.Open();
    int rows = myCommand.ExecuteNonQuery();
    myConnection.Close();
}

ContextUtil是用于获取 COM+ 上下文信息的首选类。由于此类的成员全部为static,因此在使用其成员之前不需要对此类进行实例化。
ASP.NET页面事务的优势和限制如下。
l  优势:实现简单,不需要额外的编码。
    l限制:页面的所有代码都是同一个事务,这样的事务可能会很大,而也许我们需要的是分开的、小的事务实现在Web层。
     选自《亮剑.NET. .NET深入体验与实战精要》一书 5.4 节。

1楼 2016/05/28 20:02
您未登录,没有发贴权限[点此登录]