1、外部事務
在外部開啟事務的場景,可使用 WithTransaction 傳入事務對象。
await fsql.Update<xxx>()
.WithTransaction(指定事務)
.Set(a => a.Clicks + 1)
.ExecuteAffrowsAsync();
ISelect、IInsert、IUpdate、IDelete,都支持 WithTransaction 方法。
2、同線程事務
同線程事務,由 fsql.Transaction 管理事務提交回滾(缺點:不支持異步),比較適合 WinForm/WPF UI 主線程使用事務的場景。
用戶購買了價值100元的商品:扣余額、扣庫存。
fsql.Transaction(() => {
//fsql.Ado.TransactionCurrentThread 獲得當前事務對象
var affrows = fsql.Update<User>()
.Set(a => a.Wealth - 100)
.Where(a => a.Wealth >= 100).ExecuteAffrows();
//判斷別讓用戶余額扣成負數
if (affrows < 1)
throw new Exception("用戶余額不足");
//拋出異常,回滾事務,事務退出
affrows = fsql.Update<Goods>()
.Set(a => a.Stock - 1)
.Where(a => a.Stock >= 1).ExecuteAffrows();
//判斷別讓用庫存扣成負數
if (affrows < 1)
throw new Exception("商品庫存不足");
//拋出異常,回滾事務,事務退出
});
同線程事務使用簡單,需要注意的限制:
-
事務對象在線程掛載,每個線程只可開啟一個事務連接,嵌套使用的是同一個事務;
-
事務體內代碼不可以切換線程,因此不可使用任何異步方法,包括FreeSql提供的數據庫異步方法(可以使用任何 Curd 同步方法);
系列文章導航
-
(二十八)事務
