示例#1
0
        public IActionResult NewProduct(ProductsNewProductViewModel vm)
        {
            if (ModelState.IsValid)
            {
                Products Product = new Products
                {
                    Name        = vm.Name,
                    ImageUrl    = vm.ImageUrl,
                    Price       = vm.Price,
                    Grade       = vm.Grade,
                    Stock       = vm.Stock,
                    DateCreated = DateTime.Now
                };
                _context.Add(Product);

                IEnumerable <string> categories = _context.categories.Select(x => x.CategoryName).ToList();
                foreach (string TestCategory in vm.Category)
                {
                    if (categories.Contains(TestCategory))
                    {
                        Console.WriteLine("Category: " + TestCategory + "is in database");
                    }
                    else
                    {
                        Console.WriteLine("Category: " + TestCategory + " is NOT in database, ADDING!");

                        //Here code to add new category to database
                        Category category = new Category
                        {
                            CategoryName = TestCategory,
                            Description  = "NULL"
                        };
                        _context.Add(category);
                    }

                    //Adding date to merge Table
                    ProductCategory productCategory = new ProductCategory
                    {
                        ProductId    = Product.ProductId,
                        CategoryName = TestCategory
                    };
                    _context.Add(productCategory);
                }

                _context.SaveChanges();
            }

            return(View());
        }
示例#2
0
 public void Add(Products NewProduct)
 {
     _context.Add(NewProduct);
     _context.SaveChanges();
 }