仓储事务
try { // 开启事务,使用 SqlSugarClient 的 Context 来管理 var db = _userListRep.Context; await db.AsTenant().BeginTranAsync(); // 操作第一个表 var entity1 = input.Adapt<CePingUserList>(); await _userListRep.AsUpdateable(entity1).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync(); await _userListRep2.DeleteAsync(entity2); // SQL 操作 // 提交事务 await db.AsTenant().CommitTranAsync(); } catch (Exception ex) { // 如果发生异常,回滚事务 await _userListRep.Context.RollbackTranAsync(); throw new Exception("事务执行失败", ex); }
public async Task<int> test2() { var db2 = _sysUserRep.Context; try { await db2.AsTenant().BeginTranAsync(); var entity = await _sysUserRep.GetFirstAsync(u => u.Id == 1); await _sysUserRep.DeleteAsync(entity); //真删除 var entity2 = await _sysUserRep.GetFirstAsync(u => u.Id == 3); await _sysUserRep.DeleteAsync(entity2); var aaa = await _sysUserRep.GetListAsync(); // SQL 操作 // 提交事务 await db2.AsTenant().CommitTranAsync(); return 1; } catch (Exception) { await db2.AsTenant().RollbackTranAsync(); return 2; } finally { } }