2014年12月3日 星期三

[Entity Framework 6] Transaction

.NET   Entity Framework    ORM

背景

如何在Entity Framwwork採用Transaction,以提供Commit/Rollback的功能。
以及觀察在過程中的連線狀態。

環境

l   Windows 7 pro
l   MS Sql Server 2012
l   Visual Studio 2013 updat4 (C#)


實作

原始程式碼

protected System.Data.Entity.DbContext _dbContext = null;

public void TestConnection_noTrans(out bool isConnectionOK)
{
try{

this._dbContext.Database.ExecuteSqlCommand("INSERT INTO HILO VALUES('TEST1',1,1000)");
        this._dbContext.Database.ExecuteSqlCommand("INSERT INTO HILO VALUES('TEST2',1,3000)");
        this.printConnectionState(this._dbContext); //===>連線狀態 : Closed
        isConnectionOK = true;
    }
    catch (Exception ex){
        isConnectionOK = false;
throw;
    }
}



Transaction : Example 1

protected System.Data.Entity.DbContext _dbContext = null;

public void TestConnection(out bool isConnectionOK)
{
   try{

     this.printConnectionState(this._dbContext); //連線狀態 : Closed
using (var dbContextTransaction = this._dbContext.Database.BeginTransaction())
     {
        this._dbContext.Database.ExecuteSqlCommand("INSERT INTO HILO VALUES('TEST1',1,1000)");
        this._dbContext.Database.ExecuteSqlCommand("INSERT INTO HILO VALUES('TEST2',1,3000)");

        this.printConnectionState(this._dbContext); //連線狀態 : Open

        dbContextTransaction.Commit();
        //dbContextTransaction.Rollback();
      }

      this.printConnectionState(this._dbContext); //連線狀態 : Closed
      isConnectionOK = true;
}
  catch (Exception ex){
       isConnectionOK = false;
       throw;
   }
}



Transaction : Example 2

public void TestConnection(out bool isConnectionOK)
{
   try{

using (var dbContextTransaction = this._dbContext.Database.BeginTransaction())
     {
        foreach (var csv in csvList)
        {
            this._dbContext.TmsSDP.Add(csv);

        }
        this._dbContext.SaveChanges();

          dbContextTransaction.Commit();
         //dbContextTransaction.Rollback();
      }

      this.printConnectionState(this._dbContext); //連線狀態 : Closed
      isConnectionOK = true;
}
  catch (Exception ex){
       isConnectionOK = false;
       throw;
   }
}



Reference



沒有留言:

張貼留言