ASP. NET Transactions can be said to be in . Net One of the simplest ways to implement transactions on the platform, you only need one lineCodeYou can. In Aspx Add an additional attribute in the page declaration, that is, the transaction attribute. Transaction = "required" , Which has the following values: Disabled (Default ), Notsupported , Supported , Required And Requiresnew , These settings and COM + Like the settings in enterprise-level services, a typical example is to set a transaction Required . If the page contains user controls, these controls are also included in transactions, where transactions exist in every place on the page.
Page DeclarationTransaction = "required":
<%@ PageTransaction = "required" Language = "C #" autoeventwireup = "true"
Codebehind = "webform3.aspx. cs" inherits = "webapplication4.webform3"%>
Page reference:Using system. enterpriseservices;.
Then, the data operation code is as follows:
Protected void button#click (Object sender, eventargs E)
{
Try
{
Work1 ();
Work2 ();
Contextutil. setcomplete ();//Commit transactions
}
Catch (system. Exception doesn't)
{
Contextutil. setabort ();//Cancel transaction
Response. Write (Response T. 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 ();
}
ContextutilYesCOM +The preferred class for context information. Because all the members of this class areStaticTherefore, you do not need to instantiate this class before using its members.
ASP. NETThe advantages and limitations of page transactions are as follows.
LAdvantage: it is easy to implement and requires no additional encoding.
LRestrictions: All the code on the page is the same transaction, and such a transaction may be very large. However, what we may need is a separate, small task. Web Layer.
This is Part 1 of the book Liang Jian. net.. Net deep experience and practical needs.