Dapper 事务 Transaction
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當然也不會忘記。
//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(); } }
單一資料庫時建議使用(效能較好)。
//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