Example #1
0
        public IActionResult Create(Product item)
        {
            _context.Products.Add(item);
            _context.SaveChanges();

            return(CreatedAtRoute("GetProduct", new { id = item.Id }, item));
        }
Example #2
0
        public void Delete(int id)
        {
            User user = context.Users.Find(id);

            context.Users.Remove(user);
            context.SaveChanges();
        }
Example #3
0
        private static void TestEFProduct()
        {
            using (var context = new CatalogContext())
            {
                context.ProductGroups.Add(ProductGroup.Create("Rosa"));
                context.ProductGroups.Add(ProductGroup.Create("Gerbera"));
                context.ProductGroups.Add(ProductGroup.Create("Tulip"));

                context.SaveChanges();

                var rosa   = context.ProductGroups.Where(pg => pg.Name == "Rosa").SingleOrDefault();
                var rosaId = context.Entry(rosa).Property("ProductGroupId").CurrentValue;

                var tulip = context.ProductGroups.Where(pg => Microsoft.EntityFrameworkCore.EF.Property <int>(pg, "ProductGroupId") == 3).SingleOrDefault();

                var redBerlin = Product.Create(rosa, "R GR Red Berlin", null, "R GR Red Berlin");
                var ajax      = Product.Create(tulip, "TU EN AJAX", null, "TU EN AJAX");
                context.Products.Add(redBerlin);
                context.Products.Add(ajax);

                context.SaveChanges();
            }

            var productGroups = CatalogQueries.GetProductGroups();
        }
Example #4
0
        public T Add(T entity)
        {
            _dbContext.Set <T>().Add(entity);
            _dbContext.SaveChanges();

            return(entity);
        }
        public void Remove(int id)
        {
            //Apagando empresa
            var empresa = _context.Empresa.Where(x => x.Id == id).FirstOrDefault();

            _context.Empresa.Remove(empresa);
            _context.SaveChanges();
        }
Example #6
0
 public ActionResult Create([Bind(Include = "Id,Name,Description")] Role role)
 {
     if (ModelState.IsValid)
     {
         db.Roles.Add(role);
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(role);
 }
Example #7
0
 public ActionResult Create([Bind(Include = "Id,Name,Login,Profiles")] User user)
 {
     if (ModelState.IsValid)
     {
         db.Users.Add(user);
         db.SaveChanges();
         return(RedirectToAction("AddProfilesforUser", user));//добавил юзер в параметр
     }
     return(View(user));
 }
Example #8
0
 public IActionResult Edit(CatalogProd edit_prods)
 {
     //добавляем данные в БД
     //db.CatalogProds.Add(catalogProd);
     //сохраняем данные
     db.CatalogProds.Update(edit_prods);
     db.SaveChanges();
     //возвращаем каталог
     return(RedirectToAction("Index"));
 }
Example #9
0
 public ActionResult CreateProfile([Bind(Include = "Id,Name,Roles")] Profile profile)
 {
     if (ModelState.IsValid)
     {
         db.Profiles.Add(profile);
         db.SaveChanges();
         //izmenil redurect
         return(RedirectToAction("AddRoleforProfile", profile));
     }
     return(PartialView(profile));
 }
Example #10
0
        public ActionResult Create([Bind(Include = "ID,PeriodNumber")] Period period)
        {
            if (ModelState.IsValid)
            {
                db.Periods.Add(period);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(period));
        }
        public ActionResult Create([Bind(Include = "TagId,TagName")] Tag tag)
        {
            if (ModelState.IsValid)
            {
                db.Tags.Add(tag);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(tag));
        }
Example #12
0
        public ActionResult Create([Bind(Include = "ID,Name,Instructor,Description,Capacity,CurrentStudentCount,PeriodID")] Elective elective)
        {
            if (ModelState.IsValid)
            {
                db.Electives.Add(elective);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.PeriodID = new SelectList(db.Periods, "ID", "ID", elective.PeriodID);
            return(View(elective));
        }
        public async Task <ActionResult <EventItem> > UpdateEvent(int id, EventItem eventItem)
        {
            if (id != eventItem.Id)
            {
                return(BadRequest());
            }

            _context.Entry(eventItem).State = EntityState.Modified;
            _context.SaveChanges();

            return(NoContent());
        }
        public ActionResult AddProduct(ProductCatalog productcatalog)
        {
            if (ModelState.IsValid)
            {
                pcdb.ProductCatalogs.Add(productcatalog);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.FKCatalogID = new SelectList(db.Catalogs, "CatalogID", "Code", productcatalog.Catalog_id);
            ViewBag.FKProductID = new SelectList(pdb.Products, "ProductID", "Code", productcatalog.Product_id);
            return(View(productcatalog));
        }
        public IHttpActionResult Post([FromBody] ItemCatalog item)
        {
            if (ModelState.IsValid)
            {
                _catalogContext.ItemCatalogs.Add(item);
                _catalogContext.SaveChanges();
                return(Ok(item));
            }
            else
            {
                return(BadRequest());

                throw new HttpResponseException(HttpStatusCode.PaymentRequired);
            }
        }
Example #16
0
        public async Task DeleteItemFromBasket()
        {
            var existingBasket = BasketBuilder.WithOneBasketItem();

            _catalogContext.Add(existingBasket);
            _catalogContext.SaveChanges();

            await _basketItemRepository.DeleteAsync(existingBasket.Items.FirstOrDefault());

            _catalogContext.SaveChanges();

            var basketFromDB = await _basketRepository.GetByIdAsync(BasketBuilder.BasketId);

            Assert.Equal(0, basketFromDB.Items.Count);
        }
Example #17
0
        public IActionResult Post(string sku, [FromBody] int quantity)
        {
            Product item = _context.Products.Where(b => b.SKU.Contains(sku)).First();

            if (item == null)
            {
                return(NotFound());
            }

            item.Quantity = quantity;

            _context.Products.Update(item);
            _context.SaveChanges();
            return(NoContent());
        }
Example #18
0
        //[HttpPost("Catalog")]
        public IEnumerable <string> Create(ProductCreate productCreate)
        {
            //Validate before save to db
            var validationResults = productCreate.Validate();

            if (validationResults.Count() > 0)
            {
                return(validationResults);
            }

            //Map Dto to Models
            var productModel = Mapper.Map <Dto.ProductCreate, Models.Product>(productCreate);

            //Add productModel
            catalogContext.Add(productModel);

            //Add productGender
            foreach (var genderId in productCreate.Genders)
            {
                var productGender = new Models.ProductGender
                {
                    GenderId  = genderId,
                    ProductId = productModel.Id
                };
                catalogContext.ProductGender.Add(productGender);
            }

            //Commit changes to db
            catalogContext.SaveChanges();
            return(validationResults);
        }
        static void Main(string[] args)
        {
            var ctx = new CatalogContext();

            var course1 = new Course {
                Title = "new course", Prereq = "Nothing"
            };

            Console.WriteLine(ctx.Entry(course1).State);

            var course = (from c in ctx.Courses
                          where c.Title == "JAVA EE"
                          select c).FirstOrDefault();

            Console.WriteLine(ctx.Entry(course).State); // Unchanged

            if (course != null)
            {
                course.Prereq = "Java + SQL + HTML"; // Modified
                Console.WriteLine(ctx.Entry(course).State);
                ctx.SaveChanges();
            }
            else
            {
                Console.WriteLine("Course Not Found!");
            }
        }
        public bool InsertAnimal(M.Animal animal)
        {
            bool animalInserted = false;

            try
            {
                _dbContext.Animals.Add(animal);
                _dbContext.SaveChanges();
                animalInserted = true;
            }
            catch (Exception err)
            {
                Debug.WriteLine($"Error: {err.Message}");
            }
            return(animalInserted);
        }
Example #21
0
        public async Task Get_catalog_items_custom_page_success()
        {
            //Arrange
            var dbOptions = new DbContextOptionsBuilder <CatalogContext>()
                            .UseInMemoryDatabase(databaseName: $"{VersionPrefix}{nameof(Get_catalog_items_custom_page_success)}")
                            .Options;

            using var dbContext = new CatalogContext(dbOptions);
            dbContext.AddRange(GetFakeCatalog(20));
            dbContext.SaveChanges();

            //Act
            var orderController = new CatalogController(dbContext, mapper);
            var actionResult    = await orderController.ItemsAsync(5, 1);

            //Assert

            Assert.IsType <OkObjectResult>(actionResult);
            var page = Assert.IsAssignableFrom <PaginatedItems <ProductDTO> >((actionResult as OkObjectResult).Value);

            Assert.Equal(20, page.Count);
            Assert.Equal(1, page.PageIndex);
            Assert.Equal(5, page.PageSize);
            Assert.Equal(5, page.Data.Count());
        }
Example #22
0
        public ActionResult Save(CodelistEditModel model)
        {
            var typeName = model.Name;

            var type = _types.Where(t => t.Name == typeName).SingleOrDefault();

            if (type != null)
            {
                using (CatalogContext db = new CatalogContext())
                {
                    var keys = new object[] { model.ID };

                    var res = (ICodelist)db.Set(type).Find(keys);
                    if (res != null)
                    {
                        res.ShortDescription = model.ShortDescription;
                        res.LongDescription  = model.LongDescription;
                        res.CodelistNumber   = model.CodelistNumber;
                        res.SortOrder        = model.SortOrder;
                        db.Entry(res).State  = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            return(Redirect("~/Codelists?n=" + model.Name));
        }
Example #23
0
        public async Task Get_catalog_item_success()
        {
            //Arrange
            var dbOptions = new DbContextOptionsBuilder <CatalogContext>()
                            .UseInMemoryDatabase(databaseName: $"{VersionPrefix}{nameof(Get_catalog_item_success)}")
                            .Options;

            using var dbContext = new CatalogContext(dbOptions);
            dbContext.AddRange(GetFakeCatalog(2));
            dbContext.SaveChanges();

            //Act
            var orderController = new CatalogController(dbContext, mapper);
            var actionResult    = await orderController.ItemByIdAsync(2);

            //Assert

            Assert.IsType <ActionResult <ProductDTO> >(actionResult);
            var result = Assert.IsAssignableFrom <ProductDTO>(actionResult.Value);

            var dbItem = GetFakeCatalog(2).ElementAt(1);

            Assert.Equal(dbItem.Name, result.Name);
            Assert.Equal(dbItem.Description, result.Description);
            Assert.Equal(dbItem.ImgUri, result.ImgUri);
            Assert.Equal(dbItem.Price, result.Price);
        }
Example #24
0
        public async Task <ActionResult <bool> > Upload(int productId)
        {
            try
            {
                var existingProduct = _catalogContext.CatalogItems
                                      .Include(e => e.CatalogType)
                                      .Single(e => e.Id == productId);

                var    subFolder  = existingProduct.CatalogType.Type;
                var    file       = Request.Form.Files[0];
                string folderName = $"Pics/{subFolder}";
                if (!Directory.Exists(folderName))
                {
                    Directory.CreateDirectory(folderName);
                }
                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    string fullPath = Path.Combine(folderName, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                    existingProduct.PictureName = subFolder + "/" + fileName;
                    _catalogContext.SaveChanges();
                    await searchRepository.UpdateAsync(productId, new { PicureName = subFolder + fileName });
                }
                return(true);
            }
            catch (System.Exception ex)
            {
                return(false);
            }
        }
        public async Task GetOrderAndItemsByOrderId_When_MultipleOrdersPresent()
        {
            //Arrange
            var itemOneUnitPrice = 5.50m;
            var itemOneUnits     = 2;
            var itemTwoUnitPrice = 7.50m;
            var itemTwoUnits     = 5;

            var firstOrder = OrderBuilder.WithDefaultValues();

            _catalogContext.Orders.Add(firstOrder);
            int firstOrderId = firstOrder.Id;

            var secondOrderItems = new List <OrderItem>();

            secondOrderItems.Add(new OrderItem(OrderBuilder.TestCatalogItemOrdered, itemOneUnitPrice, itemOneUnits));
            secondOrderItems.Add(new OrderItem(OrderBuilder.TestCatalogItemOrdered, itemTwoUnitPrice, itemTwoUnits));
            var secondOrder = OrderBuilder.WithItems(secondOrderItems);

            _catalogContext.Orders.Add(secondOrder);
            int secondOrderId = secondOrder.Id;

            _catalogContext.SaveChanges();

            //Act
            var orderFromRepo = await _orderRepository.GetByIdWithItemsAsync(secondOrderId);

            //Assert
            Assert.Equal(secondOrderId, orderFromRepo.Id);
            Assert.Equal(secondOrder.OrderItems.Count, orderFromRepo.OrderItems.Count);
            Assert.Equal(1, orderFromRepo.OrderItems.Count(x => x.UnitPrice == itemOneUnitPrice));
            Assert.Equal(1, orderFromRepo.OrderItems.Count(x => x.UnitPrice == itemTwoUnitPrice));
            Assert.Equal(itemOneUnits, orderFromRepo.OrderItems.SingleOrDefault(x => x.UnitPrice == itemOneUnitPrice).Units);
            Assert.Equal(itemTwoUnits, orderFromRepo.OrderItems.SingleOrDefault(x => x.UnitPrice == itemTwoUnitPrice).Units);
        }
Example #26
0
 public static void InitializeDbForTests(CatalogContext db)
 {
     db.CatalogBrands.AddRange(GetPreconfiguredCatalogBrands());
     db.CatalogTypes.AddRange(GetPreconfiguredCatalogTypes());
     db.CatalogItems.AddRange(GetPreconfiguredItems());
     db.SaveChanges();
 }
        private void OkButton_OnClick(object sender, RoutedEventArgs e)
        {
            database.SaveChanges();

            DialogResult = true;

            Close();
        }
Example #28
0
 public void RegisterAccount(Account account)
 {
     using (CatalogContext context = new CatalogContext())
     {
         context.Accounts.Add(account);
         context.SaveChanges();
     }
 }
Example #29
0
        public CategoryController(CatalogContext context)
        {
            _context = context;

            if (_context.Categories.Count() == 0)
            {
                _context.Categories.Add(new Category {
                    Id = 1, Name = "Обувь", ParentId = 0
                });
                _context.Categories.Add(new Category {
                    Id = 2, Name = "Туфли женские", ParentId = 1
                });
                _context.Categories.Add(new Category {
                    Id = 3, Name = "Туфли мужские", ParentId = 1
                });
                _context.Categories.Add(new Category {
                    Id = 4, Name = "Открытые", ParentId = 2
                });
                _context.Categories.Add(new Category {
                    Id = 5, Name = "Закрытые", ParentId = 2
                });
                _context.Categories.Add(new Category {
                    Id = 6, Name = "Одежда", ParentId = 0
                });
                _context.Categories.Add(new Category {
                    Id = 7, Name = "Для женщин", ParentId = 6
                });
                _context.Categories.Add(new Category {
                    Id = 8, Name = "Платья", ParentId = 7
                });
                _context.Categories.Add(new Category {
                    Id = 9, Name = "Юбки", ParentId = 7
                });
                _context.Categories.Add(new Category {
                    Id = 10, Name = "Для мужчин", ParentId = 6
                });
                _context.Categories.Add(new Category {
                    Id = 11, Name = "Брюки", ParentId = 10
                });
                _context.Categories.Add(new Category {
                    Id = 12, Name = "Свитера", ParentId = 10
                });
                _context.Categories.Add(new Category {
                    Id = 13, Name = "Кроссовки", ParentId = 1
                });
                _context.Categories.Add(new Category {
                    Id = 14, Name = "Туфли детские", ParentId = 1
                });
                _context.Categories.Add(new Category {
                    Id = 15, Name = "Тапочки", ParentId = 1
                });
                _context.Categories.Add(new Category {
                    Id = 16, Name = "Сапоги", ParentId = 1
                });
                _context.SaveChanges();
            }
        }
Example #30
0
        //[HttpPost]
        //public IActionResult Post(string sku, string quantity)
        public IActionResult Post(string skuquantity)
        {
            var     _sku      = skuquantity.Substring(0, skuquantity.IndexOf("-"));
            var     _quantity = skuquantity.Substring(skuquantity.IndexOf("-") + 1);
            Product item      = _context.Products.Where(b => b.SKU.Contains(_sku)).First();

            if (item == null)
            {
                return(NotFound());
            }

            //item.SKU = _sku;
            item.Quantity = Convert.ToInt32(_quantity);
            //item.Name = item.Name;

            _context.Products.Update(item);
            _context.SaveChanges();
            return(Ok(item));
        }