public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.getUsername()); var specificPhoto = user.Photos.FirstOrDefault(x => x.Id == request.Id); if (specificPhoto == null) { throw new RestException(HttpStatusCode.NotFound, new { Photo = "Image was not found" }); } if (specificPhoto.isMain == true) { throw new RestException(HttpStatusCode.BadRequest, new { Photo = "Cannot delete main photo" }); } _photoAccessor.DeletPhoto(specificPhoto.Id); //remember to also remove it from the database user.Photos.Remove(specificPhoto); var success = await _context.SaveChangesAsync() > 0; if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); }
public async Task <Result <Unit> > Handle(Command request, CancellationToken cancellationToken) { var user = await _context.Users .Include(u => u.Photos) .FirstOrDefaultAsync(u => u.UserName == _userAccessor.GetUsername()); if (user == null) { return(null); } var photo = user.Photos.FirstOrDefault(p => p.Id == request.Id); if (photo == null) { return(null); } var result = await _photoAccessor.DeletPhoto(photo.Id); if (result == null) { return(Result <Unit> .Failure("Ошибка при удалении фото из Cloudinary")); } user.Photos.Remove(photo); var success = await _context.SaveChangesAsync() > 0; if (success) { return(Result <Unit> .Success(Unit.Value)); } return(Result <Unit> .Failure("Ошибка при удалении фото из API")); }