DAPPER 事務 TRANSACTION

老飞飞發表於2024-05-03

https://www.cnblogs.com/friend/p/16754184.html\

public async Task<int> Save(long moldProducedProductId, List<MoldStandardResource> list)
 {
   int result = 0;
   string delSql = "Delete MoldStandardResource Where MoldProducedProductId=@moldProducedProductId";
   string InsertSql = "INSERT INTO [dbo].[MoldStandardResource] ([Id],[MoldProducedProductId],[ProjectCategoryId],[CustomValue],[Description],[UserId],[UpdateDate])VALUES(@Id,@MoldProducedProductId,@ProjectCategoryId,@CustomValue,@Description,@UserId,@UpdateDate)";
   using var conn = _dapperContext.CreateConnection();
   conn.Open();
   using (var transaction = conn.BeginTransaction())
   {
     try
     {
       result = await conn.ExecuteAsync(delSql, new { moldProducedProductId }, transaction);
 
       foreach (var detail in list)
       {
         await conn.ExecuteAsync(InsertSql, detail, transaction);
       }
       transaction.Commit();
     }
     catch
     {
       transaction.Rollback();
       throw;
     }
     finally
     {
       conn?.Close();
     }
   }
   return result;
 }

  

Dapper - Transaction​
交易是如此的重要,Dapper當然也不會忘記。

  • TransactionScope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Transaction
using (SqlConnection conn = new SqlConnection(strConnection))
{
string strSql = " UPDATE Users SET col1=@c1 WHERE col2=@c2" ;
dynamic datas = new []{ new { c1 = "A", c2 = "A2" }
, new { c1 = "B", c2 = "B2" }
, new { c1 = "C", c2 = "C2" }};
//交易
using(var tran = conn.BeginTransaction())
{
conn.Execute( strSql, datas);
tran.Commit();
}
}

  單一資料庫時建議使用(效能較好)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//TransactionScope
//加入參考
using System.Transactions;
//交易
using(var tranScope = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(strConnection))
{
string strSql = " UPDATE Users SET col1=@c1 WHERE col2=@c2" ;
dynamic datas = new []{ new { c1 = "A", c2 = "A2" }
, new { c1 = "B", c2 = "B2" }
, new { c1 = "C", c2 = "C2" }};
conn.Execute( strSql, datas);
}
tranScope.Complete();
}

  用於異質資料庫交易。

參考:https://dotblogs.com.tw/OldNick/2018/01/15/Dapper#Dapper%20-%20Transaction

相關文章