# 使用特性的方式管理事务
在需要使用事物的方法上增加 [Transaction] 特性
提示
事物可跨方法,并且支持同步和异步。事务传播属性Propagation默认值为Requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中。事务隔离级别IsolationLevel为可选参数。
事物回滚:
- 返回友好提示(推荐)
return ResponseOutput.NotOk(msg);
- 直接抛出异常
throw new Exception(msg);
例如下面的用户更新,存在多个Curd操作,要么全部成功,要么全部失败。
[Transaction(Propagation = Propagation.Required)]
public async Task<IResponseOutput> UpdateAsync(UserUpdateInput input)
{
if (!(input?.Id > 0))
{
return ResponseOutput.NotOk();
}
var user = await _userRepository.GetAsync(input.Id);
if (!(user?.Id > 0))
{
return ResponseOutput.NotOk("用户不存在!");
// throw new Exception("用户不存在!");
}
_mapper.Map(input, user);
// 更新用户
await _userRepository.UpdateAsync(user);
// 删除用户角色
await _userRoleRepository.DeleteAsync(a => a.UserId == user.Id);
if (input.RoleIds != null && input.RoleIds.Any())
{
var roles = input.RoleIds.Select(a => new UserRoleEntity { UserId = user.Id, RoleId = a });
// 批量插入用户角色
await _userRoleRepository.InsertAsync(roles);
}
return ResponseOutput.Ok();
}