EFCore的事務和分佈式事務的使用

在操做數據庫的時候,事務提交時咱們必須考慮的問題,下面針對EFCore的事務進行介紹:html

1.EFCore自帶默認事務SaveChanges數據庫

EFCore 的一個Context鏈接對應的一次SaveChanges就是一個事務處理,框架

咱們能夠在一個Context裏操做多個表數據,分佈式

有對一個表進行修改,對另外一個表進行新增ide

而後一次性調用SaveChanges;測試

以下代碼:google

///DbContext SaveChanges 事務提交 事務提交   ///事務特色:要不都成功 要麼都知道   using (EFCoreContext context = new EFCoreContext())   {    SysLog log = context.SysLog.FirstOrDefault(l => l.Id == 1);    context.SysLog.Remove(log);    SysUserInfo sysUserInfo1 = context.SysUserInfo.FirstOrDefault(a => a.Id == 6);    SysUserInfo sysUserInfo2 = context.Set<SysUserInfo>().Find(5);    sysUserInfo1.Name += "-11";    sysUserInfo2.Name += "-22";    context.SysLog.Add(new SysLog()    {     UserName = "測試日誌",     Introduction = "描述一下"    });     context.SaveChanges();   }

 

2.IDbContextTransaction同一數據庫事務處理spa

//若是我須要把兩個SaveChange 事務一下的?    using (EFCoreContext context = new EFCoreContext())    {      IDbContextTransaction tans = null;     try     {      tans = context.Database.BeginTransaction(); //框架對事務的支持      context.SysLog.Add(new SysLog()      {       UserName = "第一次SaveChanges",       Introduction = "第一次SaveChanges",       CreateTime = DateTime.Now      });       context.SaveChanges();      context.SysLog.Add(new SysLog()      {       UserName = "第二次SaveChanges",       Introduction = "第二次SaveChanges",       CreateTime = DateTime.Now      });      context.SaveChanges();      tans.Commit(); //代碼只有執行到這裏事務才能生效     }     catch (Exception ex)     {      if (tans != null)      {       tans.Rollback();//事務回退      }      Console.WriteLine(ex.Message);     }     finally     {      tans.Dispose();     }    }

 

3.TransactionScope分佈式事務日誌

多個數據庫之間的事務提交用TransactionScope,也就是多個Context的提交,下面模擬多個數據庫的Contexthtm

以下代碼:

 ///若是我須要把兩個SaveChange 事務一下的?    using (EFCoreMigrationContext context1 = new EFCoreMigrationContext()) //招商銀行的數據庫    using (EFCoreMigrationContext context2 = new EFCoreMigrationContext())////中國銀行的數據庫    {     //須要引入System.Transactions.Local.dll     using (TransactionScope transactionScope = new TransactionScope())     {       try      {        context1.SysLog.Add(new SysLog()       {        UserName = "context1新增一條測試數據",        Introduction = "context1新增一條測試數據",        CreateTime = DateTime.Now       });       context1.SaveChanges();       context2.SysLog.Add(new SysLog()       {        UserName = "context2新增一條測試數據",        Introduction = "context2新增一條測試數據",        CreateTime = DateTime.Now       });        context2.SaveChanges();       transactionScope.Complete();//提交事務      }      catch (Exception ex)      {       Console.WriteLine(ex.Message);      }     }    }

 

EFCore的事務和分佈式事務的使用
楊顏玩轉站內促銷廣告google趨勢wish發佈產品價格限制政策,4個月內漲幅爲1美圓或最高20%亞馬遜VAT稅號零申報有什麼風險?新手賣家如何遵循亞馬遜政策迅田國際阿里國際站發佈三大行業發展報告,分析行業熱點! 文章轉載:http://www.shaoqun.com/a/476376.html
相關文章
相關標籤/搜索