Add transaction
Some methods may require transaction support. We may want to separate the transaction from the business, that is, when writing the businessCodeYou don't have to worry about transactions at all. Let's look at a scenario, a bank account.
The user management class has a method for transferring money. The Code is as follows:
Code
Class Accountmanager
{
Public Void Trans (account A1, account A2, Decimal Money)
{
A1.money = A1.money - Money;
A2.money = A2.money + Money;
Update (a1.accoutid, A1 );
Update (a2.accoutid, A2 );
}
Public Void Update ( Int ID, account)
{
Using (Dataclasses1datacontext DC = New Dataclasses1datacontext ())
{
VaR = DC. Account. First (T => T. accoutid = ID );
A. Money = Account. money;
DC. submitchanges ();
}
}
}
Now I don't want to modify this part of code, but I want the Trans METHOD TO BE A transaction. Below we use postsharp to implement it:
First, introduce postsharp. Laos and postsharp. Public.ProgramIn addition, the system. Transactions assembly must be introduced to add the transactionscopeattribte class:
Code
[Serializable]
Class Transactionscopeattribte: onmethodboundaryaspect
{
Public Override Void Onentry (methodexecutioneventargs eventargs)
{
Transactionoptions = New Transactionoptions ();
Transactionscopeoption = Transactionscospontion. required;
Enterpriseservicesinteropoption interopoption = Enterpriseservicesinteropoption. Automatic;
Eventargs. methodexecutiontag = New Transactionscope (transactionscopeoption, transactionoptions, interopoption );
}
Public Override Void Onexit (methodexecutioneventargs eventargs)
{
Transactionscope = (Transactionscope) eventargs. methodexecutiontag;
If (Eventargs. Exception = Null )
{
Transactionscope. Complete ();
Transactionscope. Dispose ();
}
Else
{
Transactionscope. Dispose ();
}
}
}
Then, identify the property on the method for adding the transaction
[Transactionscopeattribte]
Public static void trans (account A1, account A2, decimal money)
{
In this way, the Trans method is included in the transaction.
Note: You must enable the Distributed Transaction Coordinator service on the machine where the database is located.
Code download