Using transactions in the Entity Framework

Source: Internet
Author: User

By default, when EF calls SaveChanges (), all generated SQL commands are "wrapped" into a "transaction (transaction)", and the entire transaction is rolled back as long as one of the data update operations fails.
In most cases, if you always use one instead of multiple DbContext objects in the data Update operation code, and just call SaveChanges () at the last time, then the default transaction mechanism for EF is sufficient, and there is no need to do anything extra.
However, if the following situation occurs, you must explicitly handle the transaction.


The first scenario: you need to save the data in stages, so you need to call SaveChanges () multiple times or execute SQL commands that modify the database.


Take a look at the following sample code:

using(varContext =NewMydbcontext ()) {    Try{Person3 P=context.        People3.first (); P.name="NewName"+ (NewRandom (). Next (1, -)); Context.        SaveChanges (); Context. Database.executesqlcommand ("update Person3 setdescription={0} where Person3id={1}",                            "descriptionmodified at"+DateTime.Now.ToShortTimeString (), p.person3id); P.age*=2; Context.    SaveChanges (); }    Catch(Exception e) {Console.WriteLine (e.message); }}

In the code above, call two SaveChanges () and one more time to execute the update command.
If there is an exception in the last SaveChanges (), although the last unsuccessful, you will find that the first two data have been saved! This brings up the problem of inconsistent data.
For this scenario, you need to write the transaction code explicitly (note: The following code applies to EF6):

 using  (var  context = new   Mydbcontext ()) { using  ( Span style= "color: #0000ff;" >var  transaction =context.        Database.begintransaction ()) { try   {... context.               SaveChanges (); Context. Database.executesqlcommand (    catch   (Exception e) {               Console.WriteLine (E.message); Transaction.        Rollback (); }    }}

In particular, be sure to call commit (), I test found that, as long as no commit, even if no exception occurs, the transaction will still be rolled back, the data in the database will not be updated.

In the second case, you need to use multiple DbContext to save the data, which uses TransactionScope to commit the transaction

TransactionScope is located under the using System.Transactions; namespaces, you need to manually join in the reference. the class cannot be inherited.

    //    // Summary:     //      make a block of code transactional code. This class cannot be inherited. public    sealedclass transactionscope:idisposable

Common parameters

  1. TransactionScopeOption
    ////Summary://the scope requires a transaction. If an environment transaction already exists, the environment transaction is used. Otherwise, a new transaction is created before the scope is entered. This is the default value. Required=0,////Summary://A new transaction is always created for the scope. RequiresNew=1,////Summary://the environment transaction context was canceled when the scope was created. All operations in the scope are completed without an ambient transaction context. Suppress=2

  2. TimeSpan setting time-out
            //        //Summary://Initializes a new instance of the System.Transactions.TransactionScope class with the specified time-out value and requirements. //        //Parameters://scopeoption://an instance of the System.Transactions.TransactionScopeOption enumeration that describes the transaction requirements associated with this transaction scope. //        //scopetimeout://after System.TimeSpan, the transaction scope will time out and abort the transaction.          PublicTransactionScope (transactionscopeoption scopeoption, TimeSpan scopetimeout);

Advantages:

    1. It is more convenient to use. TransactionScope can implement implicit transactions, allowing you to write data access layer code without taking into account the transaction, while at the business level of the control transaction.
    2. You can implement distributed transactions, such as cross-Library or MSMQ.
    3. Deadlock issues can be resolved in multiple contexts of dbcontexttransaction in EntityFramework. This means that when using TransactionScope transactions in EF, there is no need to consider the multi-context problem of database operations.

Disadvantages:

    1. This way, for a database lock table, it affects the query of other processes, that is, for locked tables, queries are locked, dirty reads are not allowed, and other queries need to wait. The point is that configuration modifications cannot be made.
    2. This approach requires multi-threaded locking for the same range/same logical operation, or it throws an exception when multiple threads open the same transaction.
    3. Deadlocks can also occur when locking the same table in multiple transactional operations

Examples of usage are as follows:

Test1 _context =NewTest1 (); Test1 _context2=NewTest1 ();using(TransactionScope tran =NewTransactionScope ()) {    Try    {        //1. Modify the provinceArea province = _context. Areas.firstordefault (q = Q.arealevel = =1); Province. AreaName= Province. AreaName +"1"; _context.        SaveChanges (); Console.WriteLine (_context2. Areas.firstordefault (q= = Q.arealevel = =1).        AreaName); //2. Revision of the cityArea city = _context2. Areas.firstordefault (q = Q.arealevel = =2); City. AreaName= City. AreaName +"1"; _context2.        SaveChanges (); //Throw Exception        Throw NewException ("To test a transaction exception");    Tran.complete (); }    Catch(Exception ex) {Console.WriteLine ("Execution Error:"+Ex.    Message); }}

Special Note:
If your context (DbContext) has only one in the program, then if an exception occurs during the execution of a transaction causing the transaction to be rolled back, the data model and data in the database do not correspond, that is, the database operation is rolled back, But the state of each data model in EF becomes a transactional commit, but the transaction is actually rolled back. the current official advice for this issue is that if the transaction is rolled back in EF, the old context (DbContext) is discarded and a new context (DbContext) is used.

Reference documents:

Transaction operations in Entiryframework (ii) TransactionScope

EntityFramework transaction Processing

Using transactions in the Entity Framework

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.