private void Validate(IPersistenceUnitOfWork uow, Entities.Security.User userToDelete) { // user has assigned to site var userId = userToDelete.Id; var site = uow.Context.Query <Entities.Sites.Site>().FirstOrDefault(s => s.Users.Any(u => u.Id == userId)); if (site != null) { throw new ValidationException($"User is assigned to site: {site.Name}"); } // user is creator of post if (uow.Context.Query <Entities.Posts.Post>().Any(p => p.Creator.Id == userId)) { throw new ValidationException("User has associated post entry, please delete all user's posts first and try again"); } // user is owner of job if (uow.Context.Query <Entities.Jobs.Job>().Any(j => j.Owner.Id == userId)) { throw new ValidationException($"User has jobs, please delete all user's jobs first and try again."); } }
protected override void OnHandle(AddUserCommand command) { using (var uow = UowFactory.Create()) { Validate(command, uow); Person person = null; if (command.IsIndividual) { person = new Person { Title = command.Title, GivenName = command.GivenName ?? "", Surname = command.Surname ?? "" }; if (!string.IsNullOrWhiteSpace(command.PhoneNumber)) { person.Telephones.Add(new Telephone { Type = TelephoneTypes.Mobile, Number = command.PhoneNumber, Party = person }); } uow.Context.Add(person); } var newUser = new Entities.Security.User { UserName = command.UserName, Email = command.Email, SecurityStamp = Guid.NewGuid().ToString(), // initialize security stamp with a random value AccessFailedCount = 0, IsSystemUser = command.IsSystemUser, PasswordHashAlgorithm = HashAlgorithm.PBKDF2.ToString(), Status = UserStatus.Active, Party = person, PhoneNumber = command.PhoneNumber, EmailConfirm = false, PhoneNumberConfirmed = false, }; foreach (var roleId in command.RoleIds) { var role = uow.Context.FindById <Entities.Security.Role>(roleId); if (role == null) { throw new EntityNotFoundException($"Role (id={roleId}) not found"); } newUser.Roles.Add(role); } uow.Context.Add(newUser); var ctx = uow.Context as IPersistenceContextExplicit; if (ctx != null) { ctx.Flush(); } foreach (var siteId in command.SiteIds) { var site = uow.Context.FindById <Entities.Sites.Site>(siteId); if (site == null) { throw new EntityNotFoundException($"Site (id={siteId}) not found"); } site.Users.Add(newUser); } uow.Complete(); } }