(GO). NET advanced step, under the complex business logic, how to write the transaction code with the most concise code, the most intuitive?

Source: Internet
Author: User
Tags shallow copy

Original address: http://www.cnblogs.com/1996V/p/7798111.html

Example One and example two, mainly to explain what TransactionScope is, why use TransactionScope.
Example three (important) is to optimize the wording, to increase the flexibility and readability of the code.

"Example One"

Now, you want to write an inbound interface, the general meaning is: tick a product, and then write the number, click the Inbound button, will produce a record, and the corresponding inventory quantity of this commodity will also be updated.
Because inventory is involved, transactions are used to ensure data security.

Storagetask: Warehousing operation table, storage record

Goodsinventory: Commodity inventory table, which contains a detailed description of the different products, quantity and other information

Then our realization may be so,

The code, we mainly first look at the commodity warehousing operation Goodsinventoryoperate This Dal method, put the diagram:

Above this is a Dal method, the transaction is very popular, very general, the code is not wrong.

"Example Two"

OK, now, our business requirements to change, change to this:

Tick a commodity, enter the number of items in the item, and then tick a raw material, enter the quantity of the raw material, the final click on the storage button, to produce the goods into the storage record and raw material storage records, but also to modify the corresponding commodity inventory table and raw Material Inventory table inventory quantity

So, we're going to modify this interface, first of all, the parameters are changed from the original single-line parameter to the parameter in the set form.

Then our interface code is also modified, such as:

And then we're looking at this inbound operation method Inventoryoperate

We compare, we put the previous commodity warehousing operation Goodsinventoryoperate method to change into the warehousing operation method Inventoryoperate.

In fact, the warehousing operation method inventoryoperate = Goods warehousing operations + raw material warehousing operations, but because of business changes, let us have to the original DAL layer two method code to copy paste together, form a third method, that is, warehousing operation Method Inventor Yoperate.

So, is there a way to make it easier and easier to write a transaction without having to copy and paste the code every time?

Yes!

TransactionScope:

  In the early. NET ERA, if you wanted to use transactions, you would do it with SqlTransaction, and each sqltransaction would use the same SqlConnection to connect to the object.
If the logic is simple enough to say, if the logic is a little more complicated, and want to use multiple Dal method to combine a transaction together, it is very brain, like the above evolution of the first and second edition.
To this end, in the. Net2.0 era, TransactionScope was born, Microsoft Official description: code block transactions, there is another nickname: Distributed transactions.
It implements the IDisposable interface, which can be instantiated to start with the code between dispose of as a transaction, that is, its existence, and ultimately let your code block nested in which multiple Dal methods become "a method"

So, when we use it, we can write it like this:

"Example three"

Now that you have a basic impression of TransactionScope , now that you are considering the readability and flexibility of the code, I'm going to rewrite the current style again and make the code more structured in the form of a delegate.

1///<summary>2///Unified execution of Transaction statements3///</summary>4///<param name= "AC" >Commissioned</param>5///<returns></returns>6PublicStaticboolTransactionexecute (Action AC)7{8Try9{10using (TransactionScope ts =NewTransactionScope ())11 {12  AC. Invoke (); 13  Ts.complete (); 14 }15 return true; }17 catch18  {19  return false; }21}        

Then, the encoding of our interface method becomes this:

1///<summary>2///Warehousing operations for commodity warehouses3///</summary>4///<param name= "IData" >Inbound data collection</param>5///<returns></returns>6PublicString Warehousegoodsoperate (List<inboundmodel>IData)7{8 Action ac = () = () = {};//Declaring a delegate9foreach (Inboundmodel ItemInchIData)10{11if (Item.type = ="Commodity")12{AC + = () =14{15Iservices.insert (item);16Iservices.updategoods (item);17};18}19if (Item.type = ="Raw materials")20{AC + = () =22{23Iservices.insert (item);24Iservices.updateinventory (item);25};26 }27 }28 if (iservices.transactionexecute (AC) 29  {30 return "  success ;< Span style= "COLOR: #008080" >31 }32 return "  failed ; 33}             

Through the above way of writing, eventually make the code style cleaner, at the same time in transaction processing more flexible and convenient, we just need to execute the method to let AC packet in, and finally in call Transactionexecute Unified execution.

Based on their own scenes can be customized to their own transactionexecute, this paper stresses the use of delegation to optimize the coding ideas in this case, as for Transactionexecute, here is just a simple science, which has more to dig in the place, Interested in children's shoes can be self-Baidu.

Of course, the use of this type of delegation should be noted:

Because the class is a reference type, the address and value type are passed differently, so ultimately your delegate executes the last change you made to the instance, so you think that can be done, in fact, it can't be done.

So, how to solve this situation?
Assign values individually, or with reflection?
No, we can implement the Clone method by inheriting the ICloneable interface and then using a shallow copy.

    Classicloneable    {        objectthis. MemberwiseClone (); } }

Finally, we can do this:

It's much easier to make the right program faster than to make the fast program correct.

(GO). NET advanced step, under the complex business logic, how to write the transaction code with the most concise code, the most intuitive?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.