protected override async Task Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            var product = await _uow.ProductRepository.GetWithCategoriesAsync(request.ProductId);

            _mapper.Map(request.ProductDto, product); //why we use automapper directly but create an abstraction for entity framework?

            var newCategoryIds     = request.ProductDto.CategoryIds;
            var currentCategoryIds = product.ProductCategories.Select(x => x.CategoryId).ToList();

            //delete not existing in DTO categories
            foreach (var category in product.ProductCategories
                     .Where(x => !newCategoryIds.Contains(x.CategoryId)).ToList())
            {
                product.ProductCategories.Remove(category);
            }

            //new categories
            foreach (var categoryId in newCategoryIds.Except(currentCategoryIds))
            {
                product.ProductCategories.Add(new ProductCategory
                {
                    CategoryId = categoryId,
                    ProductId  = product.Id
                });
            }

            _uow.ProductRepository.Update(product); // update ModifiedAt and ModifiedBy properties

            await _uow.SaveChangesAsync();
        }
Beispiel #2
0
        protected override async Task Handle(DeleteProductCommand request, CancellationToken cancellationToken)
        {
            var product = await _uow.ProductRepository.GetWithCategoriesAsync(request.ProductId);

            _uow.ProductCategoryRepository.RemoveRange(product.ProductCategories);
            _uow.ProductRepository.Remove(product);

            await _uow.SaveChangesAsync();
        }