コード例 #1
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var existingUser = await _context.Users
                                   .Include(qu => qu.Photos)
                                   .SingleOrDefaultAsync(u => u.UserName == _userAccessor.GetCurrentUserName());

                if (existingUser == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized, "Unauthorized access");
                }

                var userPhoto = existingUser.Photos.FirstOrDefault(p => p.Id == request.Id);

                if (userPhoto == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, "Photo does not exist");
                }
                if (userPhoto.IsMain)
                {
                    throw new RestException(HttpStatusCode.BadRequest, "Main Photo cannot be delete");
                }

                var deleteResult = await _photoAccessor.DeleteFileAsync(userPhoto.Id);

                if (deleteResult == null)
                {
                    throw new RestException(HttpStatusCode.InternalServerError, "Problem deleting the photo");
                }

                existingUser.Photos.Remove(userPhoto);

                var success = await _context.SaveChangesAsync() > 0;

                if (!success)
                {
                    throw new RestException(HttpStatusCode.InternalServerError, "Problem saving changes");
                }


                return(Unit.Value);
            }