要么就一次全成功,要么就一次全失败,插入主表的同时插入关联的子表,主表插入时返回当前插入的主键,字表插入时用这个主键做关联。
参考代码如下:
/// <summary> /// 添加角色(同时添加用户,一个数据库事务里进行处理) /// </summary> /// <param name="userInfo">用户</param> /// <param name="entity">实体</param> /// <param name="userIds">用户主键数组</param> /// <param name="statusCode">返回状态码</param> /// <param name="statusMessage">返回状态信息</param> /// <returns>主键</returns> public string AddWithUser(BaseUserInfo userInfo, BaseRoleEntity entity, string[] userIds, out string statusCode, out string statusMessage) { var parameter = ServiceParameter.CreateWithMessage(userInfo , MethodBase.GetCurrentMethod() , this.serviceName , AppMessage.RoleService_Add); string result = string.Empty; string returnCode = string.Empty; string returnMessage = string.Empty; ServiceUtil.ProcessUserCenterWriteDbWithTransaction(userInfo, parameter, (dbHelper) => { // 这里是判断已经登录的用户是否有调用当前函数的权限,加强服务层被远程调用的安全性的 var permissionManager = new BasePermissionManager(userInfo); if (permissionManager.CheckPermissionByUser(userInfo.Id, "RoleAdmin.Add", "添加角色")) { string tableName = userInfo.SystemCode + "Role"; var manager = new BaseRoleManager(dbHelper, userInfo, tableName); result = manager.Add(entity, out returnCode); if (!string.IsNullOrEmpty(result) && userIds != null && userIds.Length > 0) { tableName = userInfo.SystemCode + "UserRole"; var userManager = new BaseUserManager(dbHelper, userInfo, tableName); // 小心异常,检查一下参数的有效性 if (userIds != null) { userManager.AddToRole(userIds, result); } } returnMessage = manager.GetStateMessage(returnCode); } }); statusCode = returnCode; statusMessage = returnMessage; return result; }