public void Add(AddUserInput input) { this.Trim(input); input.Validate(); if (input.AccountName.IsNullOrEmpty() && input.MobilePhone.IsNullOrEmpty() && input.Email.IsNullOrEmpty()) { throw new InvalidInputException("用户名/手机号码/邮箱至少填一个"); } string accountName = null; if (input.AccountName.IsNotNullOrEmpty()) { accountName = input.AccountName.ToLower(); CommonTool.EnsureAccountNameLegal(accountName); bool exists = this.DbContext.Query <Sys_User>().Where(a => a.AccountName == accountName).Any(); if (exists) { throw new InvalidInputException("用户名[{0}]已存在".ToFormat(input.AccountName)); } } string mobilePhone = null; if (input.MobilePhone.IsNotNullOrEmpty()) { mobilePhone = input.MobilePhone; if (CommonTool.IsMobilePhone(mobilePhone) == false) { throw new InvalidInputException("请输入正确的手机号码"); } bool exists = this.DbContext.Query <Sys_User>().Where(a => a.MobilePhone == mobilePhone).Any(); if (exists) { throw new InvalidInputException("手机号码[{0}]已存在".ToFormat(mobilePhone)); } } string email = null; if (input.Email.IsNotNullOrEmpty()) { email = input.Email.ToLower(); if (CommonTool.IsEmail(email) == false) { throw new InvalidInputException("请输入正确的邮箱地址"); } bool exists = this.DbContext.Query <Sys_User>().Where(a => a.Email == email).Any(); if (exists) { throw new InvalidInputException("邮箱地址[{0}]已存在".ToFormat(input.Email)); } } Sys_User user = new Sys_User(); user.AccountName = accountName; user.Name = input.Name; user.Gender = input.Gender; user.MobilePhone = mobilePhone; user.Birthday = input.Birthday; user.WeChat = input.WeChat; user.Email = email; user.Description = input.Description; user.State = AccountState.Normal; string userSecretkey = KeyTool.GetEncryptKey(); string encryptedPassword = EncryptHelper.DesEncrypt(input.Password, userSecretkey); Sys_UserLogOn logOnEntity = new Sys_UserLogOn(); logOnEntity.Id = IdHelper.CreateStringSnowflakeId(); logOnEntity.UserId = user.Id; logOnEntity.UserSecretkey = userSecretkey; logOnEntity.UserPassword = encryptedPassword; List <string> roleIds = input.GetRoles(); List <Sys_UserRole> userRoles = roleIds.Select(a => { return(new Sys_UserRole() { Id = IdHelper.CreateStringSnowflakeId(), UserId = user.Id, RoleId = a, }); }).ToList(); user.RoleIds = string.Join(",", roleIds); List <string> orgIds = input.GetOrgs(); List <Sys_UserOrg> userOrgs = orgIds.Select(a => { return(new Sys_UserOrg() { Id = IdHelper.CreateStringSnowflakeId(), UserId = user.Id, OrgId = a, DisablePermission = false }); }).ToList(); user.OrgIds = string.Join(",", orgIds); List <string> postIds = input.GetPosts(); List <Sys_UserPost> userPosts = postIds.Select(a => { return(new Sys_UserPost() { Id = IdHelper.CreateStringSnowflakeId(), UserId = user.Id, PostId = a }); }).ToList(); user.PostIds = string.Join(",", postIds); this.DbContext.DoWithTransaction(() => { this.DbContext.Insert(user); this.DbContext.Insert(logOnEntity); this.DbContext.InsertRange(userRoles); this.DbContext.InsertRange(userOrgs); this.DbContext.InsertRange(userPosts); }); }