Пример #1
0
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ImportCategoryProductDTO[]), new XmlRootAttribute("CategoryProducts"));

            var categoriesDTO = (ImportCategoryProductDTO[])xmlSerializer.Deserialize(new StringReader(inputXml));

            var categoryProducts = new List <CategoryProduct>();

            var products = context.Products.ToList();

            var categories = context.Categories.ToList();


            foreach (var item in categoriesDTO)
            {
                if (categories.Any(x => x.Id == item.CategoryId) &&
                    products.Any(x => x.Id == item.ProductId))
                {
                    var catProd = new CategoryProduct
                    {
                        CategoryId = item.CategoryId,
                        ProductId  = item.ProductId
                    };

                    categoryProducts.Add(catProd);
                }
            }

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();


            return($"Successfully imported {categoryProducts.Count}");
        }
Пример #2
0
        public ActionResult MyPanel(string searchName, CategoryProduct category)
        {
            var product = _productRepository.Products;

            if (!string.IsNullOrEmpty(searchName))
            {
                var enumerable = product as IList <Product> ?? product.ToList();
                var qvery      = enumerable.Where(s => s.Name.Equals(searchName)).ToList();
                if (qvery.Count != 0)
                {
                    TempData["message"] = $"Выбран товар по имени - \"{searchName}\"";
                    return(PartialView("PartialMyPanel", qvery));
                }
                TempData["message"] = $"Товара с именем - \"{searchName}\" не существует!";
                return(PartialView("PartialMyPanel", enumerable));
            }
            switch (category)
            {
            case CategoryProduct.Selling:
                product = product.Where(x => x.Category == "Selling").
                          OrderByDescending(x => x.DateCreate);
                break;

            case CategoryProduct.Gallery:
                product = product.Where(x => x.Category == "Gallery").
                          OrderByDescending(x => x.DateCreate);
                break;

            case CategoryProduct.Partners:
                product = product.Where(x => x.Category == "Partners").
                          OrderByDescending(x => x.DateCreate);
                break;
            }
            return(PartialView("PartialMyPanel", product));
        }
Пример #3
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name")] CategoryProduct categoryProduct)
        {
            if (id != categoryProduct.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try {
                    _context.Update(categoryProduct);
                    await _context.SaveChangesAsync();
                } catch (DbUpdateConcurrencyException) {
                    if (!CategoryProductExists(categoryProduct.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(categoryProduct));
        }
        private static void ImportCategoryProducts(ProductShopContext dbContext)
        {
            int[] productIds = dbContext
                               .Products
                               .Select(p => p.Id)
                               .ToArray();

            int[] categoryIds = dbContext
                                .Categories
                                .Select(c => c.Id)
                                .ToArray();

            Random random = new Random();
            List <CategoryProduct> categoryProducts = new List <CategoryProduct>();

            foreach (int product in productIds)
            {
                for (int i = 0; i < 3; i++)
                {
                    int index = random.Next(0, categoryIds.Length);
                    while (categoryProducts.Any(cp => cp.ProductId == product && cp.CategoryId == categoryIds[index]))
                    {
                        index = random.Next(0, categoryIds.Length);
                    }

                    CategoryProduct categoryProduct = new CategoryProduct(categoryIds[index], product);
                    categoryProducts.Add(categoryProduct);
                }
            }

            dbContext.CategoryProducts.AddRange(categoryProducts);
            dbContext.SaveChanges();
        }
Пример #5
0
        private static CategoryProduct[] GetCategories(Random rand)
        {
            using (var context = new ProductsShopContext())
            {
                var productIds  = context.Products.Select(p => p.Id).ToArray();
                var categoryIds = context.Categories.Select(c => c.Id).ToArray();

                var categoryProducts = new List <CategoryProduct>();

                foreach (var p in productIds)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        var index = rand.Next(0, categoryIds.Length);

                        while (categoryProducts.Any(cp => cp.ProductId == p &&
                                                    cp.CategoryId == categoryIds[index]))
                        {
                            index = rand.Next(0, categoryIds.Length);
                        }

                        var categoryProduct = new CategoryProduct
                        {
                            ProductId  = p,
                            CategoryId = categoryIds[index]
                        };

                        categoryProducts.Add(categoryProduct);
                    }
                }
                return(categoryProducts.ToArray());
            }
        }
Пример #6
0
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ImportCategoryProductDto[]),
                                                            new XmlRootAttribute("CategoryProducts"));

            var categoriesProductsDtos = (ImportCategoryProductDto[])xmlSerializer.Deserialize(new StringReader(inputXml));

            var categoriesProducts = new List <CategoryProduct>();

            foreach (var categoryProdutDto in categoriesProductsDtos)
            {
                var product  = context.Products.Find(categoryProdutDto.ProductId);
                var category = context.Categories.Find(categoryProdutDto.CategoryId);

                if (product == null || category == null)
                {
                    continue;
                }

                var categoryProduct = new CategoryProduct
                {
                    ProductId  = product.Id,
                    CategoryId = category.Id
                };

                categoriesProducts.Add(categoryProduct);
            }

            context.CategoryProducts.AddRange(categoriesProducts);
            context.SaveChanges();

            return($"Successfully imported {categoriesProducts.Count}");
        }
        //TODO Problem 04
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ImportCategoryProductDTO[]),
                                                            new XmlRootAttribute("CategoryProducts"));

            var categoryProductsDtos =
                (ImportCategoryProductDTO[])xmlSerializer.Deserialize(new StringReader(inputXml));

            //var categoryProducts = Mapper.Map<CategoryProduct[]>(categoryProductsDtos.Where(cp =>
            //    context.Categories.Any(c => c.Id == cp.CategoryId) && context.Products.Any(p => p.Id == cp.ProductId)));
            List <CategoryProduct> categoryProducts = new List <CategoryProduct>();

            foreach (var categoryProductDto in categoryProductsDtos)
            {
                if (context.Categories.Any(c => c.Id == categoryProductDto.CategoryId) &&
                    context.Products.Any(p => p.Id == categoryProductDto.ProductId))
                {
                    CategoryProduct categoryProduct = new CategoryProduct()
                    {
                        CategoryId = categoryProductDto.CategoryId,
                        ProductId  = categoryProductDto.ProductId
                    };
                    categoryProducts.Add(categoryProduct);
                }
            }

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();

            return($"Successfully imported {categoryProducts.Count}");
        }
Пример #8
0
        private async Task AddToCategories(ICollection <string> categories, string productId)
        {
            if (categories.Count > 0)
            {
                string[] categoryIds = categories.ToArray();

                for (int i = 0; i < categoryIds.Length; i++)
                {
                    CategoryProduct categoryProduct = new CategoryProduct
                    {
                        CategoryId = categoryIds[i],
                        ProductId  = productId,
                        Place      = 0
                    };

                    await this.db.CategoryProducts.AddAsync(categoryProduct);

                    await this.db.SaveChangesAsync();
                }
            }
            else
            {
                string defaultCategoryId = await this.SeedDefaultCategory();

                CategoryProduct categoryProduct = new CategoryProduct
                {
                    CategoryId = defaultCategoryId,
                    ProductId  = productId
                };

                await this.db.CategoryProducts.AddAsync(categoryProduct);

                await this.db.SaveChangesAsync();
            }
        }
Пример #9
0
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(CategoryProductImportDto[]), new XmlRootAttribute("CategoryProducts"));

            var categoryProductsDto = (CategoryProductImportDto[])serializer.Deserialize(new StringReader(inputXml));

            var categoryProducts = new List <CategoryProduct>();

            foreach (var item in categoryProductsDto)
            {
                if (context.Categories.Any(c => c.Id == item.CategoryId) && context.Products.Any(p => p.Id == item.ProductId))
                {
                    CategoryProduct categoryProduct = new CategoryProduct()
                    {
                        CategoryId = item.CategoryId,
                        ProductId  = item.ProductId
                    };

                    categoryProducts.Add(categoryProduct);
                }
            }

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();

            return($"Successfully imported {categoryProducts.Count}");
        }
        static void SetCategories()
        {
            using (var db = new ProductShopContext())
            {
                var productIds    = db.Products.Select(x => x.Id).ToArray();
                var categoriesIds = db.Categories.Select(x => x.Id).ToArray();

                var categoryProducts = new List <CategoryProduct>();
                var rnd = new Random();
                foreach (var product in productIds)
                {
                    int index = -1;
                    for (int i = 0; i < 3; i++)
                    {
                        index = rnd.Next(0, categoriesIds.Length);

                        while (categoryProducts.Any(x => x.CategoryId == categoriesIds[index] && x.ProductId == product))
                        {
                            index = rnd.Next(0, categoriesIds.Length);
                        }

                        var catPr = new CategoryProduct()
                        {
                            ProductId  = product,
                            CategoryId = categoriesIds[index]
                        };
                        categoryProducts.Add(catPr);
                    }
                }
                db.AddRange(categoryProducts);
                db.SaveChanges();
            }
        }
Пример #11
0
        //Problem04
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(CategoryProductsDto[]), new XmlRootAttribute("CategoryProducts"));

            var categoryProductsDto = (CategoryProductsDto[])serializer.Deserialize(new StringReader(inputXml));

            var categoryProducts = new List <CategoryProduct>();

            foreach (var categoryProductDto in categoryProductsDto)
            {
                var categoryIdExists = context.CategoryProducts.Any(x => x.CategoryId == categoryProductDto.categoryId);
                var productIdExists  = context.CategoryProducts.Any(x => x.ProductId == categoryProductDto.productId);

                if (!categoryIdExists && !productIdExists)
                {
                    var categoryProduct = new CategoryProduct
                    {
                        CategoryId = categoryProductDto.categoryId,
                        ProductId  = categoryProductDto.productId
                    };

                    categoryProducts.Add(categoryProduct);
                }
            }
            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();

            return($"Successfully imported {categoryProducts.Count}");
        }
 public ActionResult <CategoryProduct> Create(CategoryProduct categoryProduct)
 {
     context.CategoryProduct.Add(categoryProduct);
     context.SaveChanges();
     //return Created($"/api/categoryProduct/{categoryProduct.Id}", categoryProduct);
     return(CreatedAtAction(nameof(GetById), new { id = categoryProduct.ProductId }, categoryProduct));
 }
Пример #13
0
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XDocument doc = XDocument.Parse(inputXml);

            var categoryProductsFromXml = doc.Root
                                          .Elements()
                                          .ToList();

            List <CategoryProduct> pairs = new List <CategoryProduct>();

            foreach (var cp in categoryProductsFromXml)
            {
                CategoryProduct currentPair = new CategoryProduct();

                var categoryId = Convert.ToInt32(cp.Element("CategoryId").Value);
                var productId  = Convert.ToInt32(cp.Element("ProductId").Value);

                if (categoryId == 0 || productId == 0)
                {
                    continue;
                }

                currentPair.CategoryId = categoryId;
                currentPair.ProductId  = productId;
                pairs.Add(currentPair);
            }
            ;

            pairs = pairs.Distinct().ToList();
            context.CategoryProducts.AddRange(pairs);

            int affectedRows = context.SaveChanges();

            return($"Successfully imported {affectedRows}");
        }
Пример #14
0
        private static void ImportCategoryProducts(ProductShopContext context)
        {
            int[] productsIds = context.Products
                                .Select(p => p.Id)
                                .ToArray();

            int categoriesCount = context.Categories.Count();

            var categoryProducts = new List <CategoryProduct>();

            foreach (int productId in productsIds)
            {
                int categoryId = new Random().Next(1, categoriesCount + 1);

                var categoryProduct = new CategoryProduct
                {
                    CategoryId = categoryId,
                    ProductId  = productId
                };

                categoryProducts.Add(categoryProduct);
            }

            context.CategoryProducts.AddRange(categoryProducts);

            context.SaveChanges();
        }
Пример #15
0
        public async Task <CategoryProduct> Create(CategoryProduct categoryProduct)
        {
            if (!Validate(new CategoryProductValidation(), categoryProduct))
            {
                return(null);
            }

            var categoryProductBD = await _unitOfWork
                                    .RepositoryFactory
                                    .CategoryProductRepository
                                    .Search(x => x.Name == categoryProduct.Name);

            if (categoryProductBD != null && categoryProductBD.Any())
            {
                NotifyError("Already exists categoryProduct the same name");
                return(await Task.FromResult <CategoryProduct>(null));
            }

            await _unitOfWork
            .RepositoryFactory
            .CategoryProductRepository
            .Add(categoryProduct);

            if (await _unitOfWork.Commit())
            {
                return(await Task.FromResult(categoryProduct));
            }

            NotifyError("Error inserting entity");
            return(await Task.FromResult <CategoryProduct>(null));
        }
Пример #16
0
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ImportCategoryProductDto[]),
                                                            new XmlRootAttribute("CategoryProducts"));

            var categoryProductsDto =
                (ImportCategoryProductDto[])xmlSerializer.Deserialize(new StringReader(inputXml));

            var categoryProducts = new List <CategoryProduct>();

            var validCategoryIds = context.Categories.Select(x => x.Id);
            var validProductIds  = context.Products.Select(x => x.Id);

            foreach (var importCategoryProductDto in categoryProductsDto)
            {
                if (!validCategoryIds.Contains(importCategoryProductDto.CategoryId) ||
                    !validProductIds.Contains(importCategoryProductDto.ProductId))
                {
                    continue;
                }

                var categoryProduct = new CategoryProduct
                {
                    CategoryId = importCategoryProductDto.CategoryId,
                    ProductId  = importCategoryProductDto.ProductId
                };
                categoryProducts.Add(categoryProduct);
            }

            context.CategoryProducts.AddRange(categoryProducts);
            var result = context.SaveChanges();

            return($"Successfully imported {result}");
        }
Пример #17
0
        public ActionResult EditCategoryProduct(Guid Categoryid, int p)
        {
            ViewBag.pageNumber = p;
            CategoryProduct categoryproduct = categoryproductService.GetByID(Categoryid);

            return(View(categoryproduct));
        }
Пример #18
0
        //01 Json
        private static void SetCategories(ProductsShopDbContext db)
        {
            var productIds  = db.Products.Select(p => p.ProductId).ToArray();
            var categoryIds = db.Categories.Select(c => c.CategoryId).ToArray();

            Random rnd = new Random();

            List <CategoryProduct> categoryProducts = new List <CategoryProduct>();

            foreach (var p in productIds)
            {
                for (int i = 0; i < 3; i++)
                {
                    int index = rnd.Next(0, categoryIds.Length);
                    while (categoryProducts.Any(c => c.ProductId == p && c.CategoryId == categoryIds[index]))
                    {
                        index = rnd.Next(0, categoryIds.Length);
                    }

                    CategoryProduct cp = new CategoryProduct
                    {
                        ProductId  = p,
                        CategoryId = categoryIds[index]
                    };
                    categoryProducts.Add(cp);
                }
            }

            db.CategoryProducts.AddRange(categoryProducts);
            db.SaveChanges();
        }
        public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext.CategoriesProducts.Any())
            {
                return;
            }

            var categoriesIds = dbContext.Categories
                                .Where(x => x.ParentCartegoryId != null)
                                .Select(x => x.Id)
                                .ToList();

            var productsIds      = dbContext.Products.Select(x => x.Id).ToList();
            var categoryProducts = new List <CategoryProduct>();

            var random = new Random();

            foreach (var productId in productsIds)
            {
                var categoryIndex   = random.Next(categoriesIds.Count - 1);
                var categoryProduct = new CategoryProduct()
                {
                    ProductId  = productId,
                    CategoryId = categoriesIds[categoryIndex],
                };
                categoryProducts.Add(categoryProduct);
            }

            await dbContext.CategoriesProducts.AddRangeAsync(categoryProducts);

            await dbContext.SaveChangesAsync();
        }
        //4. Import Categories and Products
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            /*Import the categories and products ids from the provided file categories-products.xml.
             * If provided category or product id, doesn’t exists, skip the whole entry!*/

            //judge doesnt like automapper so i wont bother making a map

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List <ImportCategoriesProductsDto>), new XmlRootAttribute("CategoryProducts"));

            var categoriesProductsDtos = (List <ImportCategoriesProductsDto>)xmlSerializer.Deserialize(new StringReader(inputXml));

            List <CategoryProduct> categoryProducts = new List <CategoryProduct>();

            foreach (var categoryProductDto in categoriesProductsDtos)
            {
                if (context.Categories.Any(c => c.Id == categoryProductDto.CategoryId) && // check if both exist
                    context.Products.Any(p => p.Id == categoryProductDto.ProductId))
                {
                    CategoryProduct categoryProduct = new CategoryProduct()
                    {
                        CategoryId = categoryProductDto.CategoryId,
                        ProductId  = categoryProductDto.ProductId
                    };
                    categoryProducts.Add(categoryProduct);
                }
            }

            context.CategoryProducts.AddRange(categoryProducts);

            context.SaveChanges();

            return($"Successfully imported {categoryProducts.Count}");
        }
        public async Task <IHttpActionResult> PutCategoryProduct(int id, CategoryProduct categoryProduct)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != categoryProduct.idCategory)
            {
                return(BadRequest());
            }

            db.Entry(categoryProduct).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #22
0
        public static void ImportProductsCateogories(ProductContext context)
        {
            var products   = context.Products.ToArray();
            var categories = context.Categories.ToArray();

            var validCategoryProducts = new List <CategoryProduct>();
            var rnd = new Random();

            foreach (var product in products)
            {
                int   count   = 0;
                int[] indexes = new int[5];
                while (count < 4)
                {
                    int index = rnd.Next(0, categories.Length - 1);
                    if (!indexes.Contains(index))
                    {
                        indexes[count] = index;
                        var categoryProduct = new CategoryProduct
                        {
                            Product  = product,
                            Category = categories[index]
                        };

                        validCategoryProducts.Add(categoryProduct);

                        count++;
                    }
                }
            }

            context.AddRange(validCategoryProducts);

            context.SaveChanges();
        }
        public CategoryProduct FindWithId(int id)
        {
            CategoryProduct categoryProduct = null;

            if (id > 0)
            {
                using (SqlCommand command = new SqlCommand("SELECT * FROM CategoriesProducts WHERE Id = @Id"))
                {
                    command.Parameters.AddWithValue("Id", id);

                    context.CreateCommand(command);
                    using (SqlDataReader dataReader = command.ExecuteReader())
                    {
                        if (dataReader.Read())
                        {
                            categoryProduct = new CategoryProduct()
                            {
                                Id           = (int)dataReader[0],
                                CategoryName = (string)dataReader[1]
                            }
                        }
                        ;
                    }
                }
            }

            return(categoryProduct);
        }
    }
        private static void ImportCategoriesProducts()
        {
            using (var db = new ProductsShopContext())
            {
                var products = db.Products
                               .ToArray();

                var categories = db.Categories.ToArray();

                var categoriesProducts = new List <CategoryProduct>();

                Random r = new Random();

                foreach (var p in products)
                {
                    CategoryProduct categoryProduct = new CategoryProduct()
                    {
                        CategoryId = categories[r.Next(0, categories.Length)].Id,
                        ProductId  = p.Id,
                    };

                    categoriesProducts.Add(categoryProduct);
                }

                db.CategoriesProducts.AddRange(categoriesProducts);

                db.SaveChanges();
            }
        }
Пример #25
0
        public async Task <IActionResult> Details(int id, [Bind("Id,Name,GroupProductId")] CategoryProduct model)
        {
            if (ModelState.IsValid)
            {
                if (CategoryProductExists(id) == false)
                {
                    model.CreatedDate = DateTime.Now;
                    model.UserId      = _userManager.GetUserId(HttpContext.User);
                    _context.Add(model);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    var category = await _context.CategoryProducts.FindAsync(id);

                    category.GroupProductId = model.GroupProductId;
                    category.Name           = model.Name;
                    category.ModifiedDate   = DateTime.Now;
                    category.UserId         = _userManager.GetUserId(HttpContext.User);

                    _context.Update(category);
                    await _context.SaveChangesAsync();
                }

                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
Пример #26
0
        public ActionResult Index(string category, string searchString)
        {
            IQueryable <string> categoryQuery = from m in db.Products
                                                orderby m.Category
                                                select m.Category;
            var product = from p in db.Products
                          select p;

            if (!string.IsNullOrEmpty(searchString))
            {
                product = product.Where(s => s.Name.Contains(searchString));
            }

            if (!string.IsNullOrEmpty(category))
            {
                product = product.Where(x => x.Category == category);
            }
            var categoryVM = new CategoryProduct
            {
                CategoryProducts = new SelectList(categoryQuery.Distinct().ToList()),
                Products         = product.ToList()
            };

            return(View(categoryVM));
        }
Пример #27
0
        // ******* Task 4 - Import Categories and Products *******
        public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
        {
            var catProFromXML = XMLConverter.Deserializer <ImportCategoriesProductsDto>(inputXml, "CategoryProducts");

            var productsId  = context.Products.Select(i => i.Id).ToList();
            var categoiesId = context.Categories.Select(c => c.Id).ToList();

            var categoryProducts = new List <CategoryProduct>();

            foreach (var item in catProFromXML)
            {
                if (productsId.Contains(item.ProductId) && categoiesId.Contains(item.CategoryId))
                {
                    var newCatPro = new CategoryProduct
                    {
                        CategoryId = item.CategoryId,
                        ProductId  = item.ProductId
                    };

                    categoryProducts.Add(newCatPro);
                }
            }

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();

            return($"Successfully imported {categoryProducts.Count}");
        }
Пример #28
0
        public IHttpActionResult PostCategoryProduct(CategoryProduct categoryProduct)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.CategoryProducts.Add(categoryProduct);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (CategoryProductExists(categoryProduct.id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = categoryProduct.id }, categoryProduct));
        }
Пример #29
0
        private static List <CategoryProduct> GetCategoryProducts(ProductShopContext context)
        {
            List <CategoryProduct> categoryProducts = new List <CategoryProduct>();

            for (int productId = 1; productId <= 200; productId++)
            {
                int categoryId = new Random().Next(1, 12);

                var categoryProduct = new CategoryProduct
                {
                    ProductId  = productId,
                    CategoryId = categoryId
                };

                categoryProducts.Add(categoryProduct);
            }

            if (!context.CategoryProducts.Any())
            {
                context.CategoryProducts.AddRange(categoryProducts);
                context.SaveChanges();
            }

            return(categoryProducts);
        }
        public async Task <IActionResult> PutCategoryProduct(int id, CategoryProduct categoryProduct)
        {
            if (id != categoryProduct.ProductId)
            {
                return(BadRequest());
            }

            _context.Entry(categoryProduct).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }