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 節。