Untitled

 avatar
unknown
csharp
5 months ago
2.9 kB
77
Indexable
    public async Task<Result<Product>> UpdateProductAsync(Guid id, CreateUpdateProductDto productDto)
    {
        using (var transaction = await _unitOfWork.BeginTransactionAsync())
        {
            try
            {
                var product = await _unitOfWork.Products.GetByIdAsync(id);
                if (product == null)
                {
                    return new Result<Product> { IsSuccess = false, Message = "Product not found." };
                }

                var slug = SlugHelper.GenerateSlug(productDto.Name);
                if (await _unitOfWork.Products.IsSlugExits(slug))
                {
                    return new Result<Product> { IsSuccess = false, Message = "Slug already exists." };
                }
                _mapper.Map(productDto, product);
                product.Slug = slug;
                var existingImages = await _unitOfWork.Images.GetImagesByProductIdAsync(product.Id);
                if (existingImages.Count != 0)
                {
                    foreach (var image in existingImages)
                    {
                        await _photoService.DeletePhotoAsync("product", image.ImageUrl);
                    }
                }

                if (productDto.Images != null && productDto.Images.Any())
                {
                    product.Images = new List<ProductImage>();
                    foreach (var image in productDto.Images)
                    {
                        var uploadResult = await _photoService.AddPhotoAsync(image, "product");
                        if (uploadResult.Error == null)
                        {
                            product.Images.Add(new ProductImage
                            {
                                Id = Guid.NewGuid(),
                                ProductId = product.Id,
                                ImageUrl = uploadResult.SecureUrl.ToString(),
                                IsPrimary = product.Images.Count == 0,
                                ImageType = "Product"
                            });
                        }
                    }

                }
                _unitOfWork.Products.Update(product);
                await _unitOfWork.CompleteAsync();
                await transaction.CommitAsync();
                return new Result<Product> { IsSuccess = true, Data = product };
            }
            catch (DbUpdateConcurrencyException ex)
            {
                await transaction.RollbackAsync(); 
                return new Result<Product> { IsSuccess = false, Message = "Concurrency error: " + ex.Message };
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                return new Result<Product> { IsSuccess = false, Message = $"An error occurred: {ex.Message}" };
            }
        }
    }
Editor is loading...
Leave a Comment