.NET開發中的交易處理大比拼 之 ASP.NET頁面層級的事務

來源:互聯網
上載者:User

ASP.NET事務可以說是在.NET平台上事務實現方式最簡單的一種,你僅僅需要一行代碼即可。在aspx的頁面聲明中加一個額外的屬性,即事務屬性Transaction="Required",它有如下的值:Disabled(預設)、NotSupported、Supported、Required和RequiresNew,這些設定和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 節。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.